2012-11-18 19 views
13

Im utilizzando il seguente metodo per estrarre forma di testo HTML:htmlagilitypack - rimuovi script e stile?

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; 
    } 

problema è che anche ottenere script e style tags.

Come posso escluderli?

+0

Che dire di uno stile in linea cioè

? Lo vedo in OuterHtml, ma vorrei eliminare anche tutti gli stili in linea. – Jeremy

+1

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

risposta

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

Come posso farlo? – Jacqueline

+0

@Jacqueline Quando si esegue il codice sopra. Tutti i tag 'script' e' style' saranno rimossi da 'doc' –

+0

ahh vedo, può essere esteso per supportare commenti come anche? – Jacqueline

4

È possibile farlo utilizzando HtmlDocument classe:

HtmlDocument doc = new HtmlDocument(); 

doc.LoadHtml(input); 

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

Non dovrebbe essere 'doc.DocumentNode.SelectNodes (" // stile | // script "). ToList(). ForEach (n => n.Remove()); '? – Rubanov

+0

@Rubanov Sì, dovrebbe esserci, avevo un metodo di estensione quindi non avevo bisogno di .ToList nel mio codice. Risposta aggiornata, grazie. – johnw86

1

Alcune risposte eccellenti, System.Linq è a portata di mano!

Per un approccio non basato 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; 

} 
Problemi correlati