HtmlAgilityPack 获取父节点的 id

HtmlAgilityPack getting id of parrent node

鉴于 html 的片段和下面的代码,如果您知道源代码的一部分,例如'FileName' 你如何获得父 div 的 post ID 这可能在 dom 树中更高,并且可能有 0、1 或许多 src 具有相同的 'FileName'

我在追求“postId_19701770”

我已尝试遵循此 page and this page 我收到错误 CS1061 'HtmlNodeCollection' 不包含 '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