2011-06-08 25 views
14
<html> 
    <body> 
     <div class="main"> 
      <div class="submain"><h2></h2><p></p><ul></ul> 
      </div> 
      <div class="submain"><h2></h2><p></p><ul></ul> 
      </div> 
     </div> 
    </body> 
</html> 

में नोड से चाइल्ड नोड तक पहुँचने के लिए मैं एक HtmlDocument में एचटीएमएल लोड। तब मैंने XPath को submain के रूप में चुना। तब मुझे नहीं पता कि प्रत्येक टैग i.e h2, p अलग-अलग टैग तक कैसे पहुंचे।कैसे htmlagility पैक

HtmlAgilityPack.HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class=\"submain\"]"); 
foreach (HtmlAgilityPack.HtmlNode node in nodes) {} 

अगर मैं node.InnerText का प्रयोग मैं सभी ग्रंथों हो और InnerHtml भी उपयोगी नहीं है। अलग टैग का चयन कैसे करें?

उत्तर

25

निम्नलिखित में मदद मिलेगी:

HtmlAgilityPack.HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class=\"submain\"]"); 
foreach (HtmlAgilityPack.HtmlNode node in nodes) { 
    //Do you say you want to access to <h2>, <p> here? 
    //You can do: 
    HtmlNode h2Node = node.SelectSingleNode("./h2"); //That will get the first <h2> node 
    HtmlNode allH2Nodes= node.SelectNodes(".//h2"); //That will search in depth too 

    //And you can also take a look at the children, without using XPath (like in a tree):   
    HtmlNode h2Node = node.ChildNodes["h2"]; 
} 
2

स्मृति से, मुझे विश्वास है कि प्रत्येक Node, अपने स्वयं के ChildNodes संग्रह है अपने for…each ब्लॉक के भीतर ताकि आप node.ChildNodes निरीक्षण करने के लिए सक्षम होना चाहिए।

0

आप वंशज

var firstSubmainNodeName = doc 
    .DocumentNode 
    .Descendants() 
    .Where(n => n.Attributes["class"].Value == "submain") 
    .First() 
    .InnerText; 
लिए देख रहे हैं
संबंधित मुद्दे