如何从htmlagility包中的节点访问子节点
我将html加载到HtmlDocument
。 然后我选择XPath作为子submain
。 然后我不知道如何分别访问每个标签,即h2
, p
。
HtmlAgilityPack.HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class=\"submain\"]"); foreach (HtmlAgilityPack.HtmlNode node in nodes) {}
如果我使用node.InnerText
我得到所有文本,而InnerHtml
也InnerHtml
。 如何选择单独的标签?
以下内容将有所帮助:
HtmlAgilityPack.HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class=\"submain\"]"); foreach (HtmlAgilityPack.HtmlNode node in nodes) { //Do you say you want to access to ,
here? //You can do: HtmlNode h2Node = node.SelectSingleNode("./h2"); //That will get the first
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
。