如何从htmlagility包中的节点访问子节点


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

我将html加载到HtmlDocument中。然后我选择XPath作为submain。然后我不知道如何分别访问每个标签,即h2p

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

如果我使用node.InnerText,我会得到所有的文本,而InnerHtml也没有用处。如何选择单独的标签?

以下内容将有所帮助:

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

您正在寻找后裔

var firstSubmainNodeName = doc
   .DocumentNode
   .Descendants()
   .Where(n => n.Attributes["class"].Value == "submain")
   .First()
   .InnerText;

根据内存,我相信每个Node都有自己的ChildNodes集合,因此在您的for…each块中,您应该能够检查node.ChildNodes

相关内容

  • 没有找到相关文章

最新更新