2012-11-18 20 views
13

Im metin formu html ayıklamak için:htmlagilitypack - komut dosyasını ve stili kaldırılsın mı? Aşağıdaki yöntem kullanılarak

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

Sorun ben de senaryo ve stil etiketleri elde edilmesi.

Onları nasıl hariç tutabilirim?

+0

ne hakkında bir satır içi stil yani

? OuterHtml'de görüyorum ama tüm satır içi stilleri de çıkarmak istiyorum. – Jeremy

+1

'if (childNode.Attributes.Contains (" stil ")) { childNode.Attributes.Remove (" stil "); } if (childNode.Attributes.Contains ("sınıf")) { childNode.Attributes.Remove ("sınıf"); } ' – Jeremy

cevap

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

Bunu nasıl aktarabilirim? – Jacqueline

+0

@Jacqueline Kodun üstünde çalıştırdığınızda. Tüm 'script' ve' style' etiketleri 'doc'dan kaldırılacaktır' ' –

+0

ahh, görebilirim, gibi yorumları destekleyecek şekilde genişletilebilir mi? – Jacqueline

4

Çok HtmlDocument sınıfını kullanarak yapabilirsiniz:

HtmlDocument doc = new HtmlDocument(); 

doc.LoadHtml(input); 

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

Bu belge doc.DocumentNode.SelectNodes ("// style | // script") olmalıdır ToList(). ForEach (n => n.Remove()); '? – Rubanov

+0

@Rubanov Evet olmalıydı, bir uzantı yöntemim vardı, bu yüzden koduma .ToList gerekmiyordu. Cevap güncellendi, teşekkürler. – johnw86

1

Bazı mükemmel cevaplar, System.Linq kullanışlıdır! olmayan bir Linq bazlı yaklaşım için

:

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; 

} 
İlgili konular