[英]HtmlAgilityPack getting id of parrent node
鉴于 html 的片段和下面的代码,如果您知道 src 的一部分,例如“FileName”,您如何获得父 div 的帖子 ID,这可能位于 dom 树的更高位置,并且可能有 0、1 或多个 src相同的“文件名”
我在“postId_19701770”之后
我试图关注这个页面,这个页面我得到错误 CS1061 'HtmlNodeCollection' does not contain a definition for 'ParentNode'
namespace GetParent
{
class Program
{
static void Main(string[] args)
{
var html =
@"<body>
<div id='postId_19701770' class='b-post'>
<h1>This is <b>bold</b> heading</h1>
<p>This is <u>underlined</u> paragraph <div src='example.com/FileName_720p.mp4' </div></p>
</div>
</body>";
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
string keyword = "FileName";
var node = htmlDoc.DocumentNode.SelectNodes("//*[text()[contains(., '" + keyword + "')]]");
var parentNode = node.ParentNode;
Console.WriteLine(parentNode.Name);
Console.ReadLine();
}
}
}
您的代码不起作用的原因是因为您正在查找节点集合的ParentNode
。 您需要 select 单个节点,然后查找其父节点。
您可以通过src
搜索所有节点(集合)以及包含您要查找的数据。 拥有集合后,您可以搜索每个节点以查看您需要哪个节点或 select 来自该集合的First()
一个以获取其父节点。
var html =
@"<body>
<div id='postId_19701770' class='b-post'>
<h1>This is <b>bold</b> heading</h1>
<p>This is <u>underlined</u> paragraph <div src='example.com/FileName_720p.mp4' </div></p>
</div>
</body>";
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
string keyword = "FileName";
var node = htmlDoc.DocumentNode.SelectNodes("//*[contains(@src, '" + keyword + "')]");
var parent = node.First().ParentNode; //node is a collection so get the first node for ex.
Console.WriteLine(parent.GetAttributeValue("id", string.Empty));
// Prints
postId_19701770
您可以通过SelectSingleNode
方法专门搜索 1 个节点,而不是查找“所有”节点
var singleNode = htmlDoc.DocumentNode.SelectSingleNode(@"//*[contains(@src, '" + keyword + "')]");
Console.WriteLine(singleNode.ParentNode.GetAttributeValue("id", string.Empty));
// prints
postId_19701770
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.