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

c# html-agility-pack

<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我得到所有文本,而InnerHtmlInnerHtml 。如何选择单独的标签?

一般承认的答案

以下内容将有所帮助:

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;


Related

许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow