2012-11-18 13 views
13

Im stosując następujące metody w celu uzyskania postaci tekstu html:htmlagilitypack - usunąć skrypt i styl?

public string getAllText(string _html) 
    { 
     string _allText = ""; 
     try 
     { 
      HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); 
      document.LoadHtml(_html); 


      var root = document.DocumentNode; 
      var sb = new StringBuilder(); 
      foreach (var node in root.DescendantNodesAndSelf()) 
      { 
       if (!node.HasChildNodes) 
       { 
        string text = node.InnerText; 
        if (!string.IsNullOrEmpty(text)) 
         sb.AppendLine(text.Trim()); 
       } 
      } 

      _allText = sb.ToString(); 

     } 
     catch (Exception) 
     { 
     } 

     _allText = System.Web.HttpUtility.HtmlDecode(_allText); 

     return _allText; 
    } 

problem jest, że również uzyskać skryptów i stylów tagów.

Jak mogę je wykluczyć?

+0

Co o stylu inline tj

? Widzę to w OuterHtml, ale chciałbym również usunąć wszystkie style śródliniowe. – Jeremy

+1

'if (childNode.Attributes.Contains (" style ")) { childNode.Attributes.Remove (" style "); } if (childNode.Attributes.Contains ("class")) { childNode.Attributes.Remove ("class"); } ' – Jeremy

Odpowiedz

41
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
doc.LoadHtml(html); 

doc.DocumentNode.Descendants() 
       .Where(n => n.Name == "script" || n.Name == "style") 
       .ToList() 
       .ForEach(n => n.Remove()); 
+0

Jak przejść przez to? – Jacqueline

+0

@Jacqueline Po uruchomieniu powyższego kodu. Wszystkie znaczniki 'script' i' style' zostaną usunięte z 'doc' –

+0

ahh widzę, czy można rozszerzyć obsługę komentarzy takich jak also? – Jacqueline

4

Można to zrobić za pomocą HtmlDocument klasę:

HtmlDocument doc = new HtmlDocument(); 

doc.LoadHtml(input); 

doc.DocumentNode.SelectNodes("//style|//script").ToList().ForEach(n => n.Remove()); 
+0

Nie powinno to być 'doc.DocumentNode.SelectNodes (" // style | // script ") ToList(). ForEach (n => n.Remove()); '? – Rubanov

+0

@Rubanov Tak, powinno być, miałem metodę rozszerzenia, więc nie wymagałem .ToList w moim kodzie. Odpowiedź zaktualizowana, dzięki. – johnw86

1

znakomite odpowiedzi, System.Linq jest przydatny!

Za niedopełnienie podejścia opartego na LINQ:

private HtmlAgilityPack.HtmlDocument RemoveScripts(HtmlAgilityPack.HtmlDocument webDocument) 
{ 

// Get all Nodes: script 
HtmlAgilityPack.HtmlNodeCollection Nodes = webDocument.DocumentNode.SelectNodes("//script"); 

// Make sure not Null: 
if (Nodes == null) 
    return webDocument; 

// Remove all Nodes: 
foreach (HtmlNode node in Nodes) 
    node.Remove(); 

return webDocument; 

} 
Powiązane problemy