如何从htmlagilitypack中的节点访问子节点

时间:2011-06-08 17:07:58

标签: 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,我会收到所有文字,InnerHtml也没用。如何选择单独的标签?

3 个答案:

答案 0 :(得分:30)

以下内容将有所帮助:

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

答案 1 :(得分:4)

您正在寻找后代

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

答案 2 :(得分:2)

从记忆中,我相信每个Node都有自己的ChildNodes集合,所以在for…each区块内,您应该能够检查node.ChildNodes