HTMLAgilitypack testing parent node attribute value

c# html-agility-pack

Question

Here is what the context : I use HTMLAgilityPack to select P node like this :

var paragraphe = html.DocumentNode.SelectNodes(".//p[not(descendant::p)]");

Then using a for loop, I you like to test for each time, if the parent of this DOM element is a DIV and contains a specific attribute such as : div[@edth_correction='N']

But I have no idea how to get the parent node, I have already written all the code for the work I have to do.

I know that I can do something like this : paragraphe[i].ParentNode.Attributes.Equals() but I have no idea what to write in this Equals and if it is what I have to use for my case.

Accepted Answer

Try this way

var paragraphe = html.DocumentNode.SelectNodes(".//p[not(descendant::p)]");

for (int i = 0; i < paragraphe.Count; i++)
{
    var parent = paragraphe[i].ParentNode;

    if (parent.Name == "div" &&
        parent.ChildAttributes("edth_correction").Any(a => a.Value == "N"))
    {
        // do work
    }
}

Another way: check the parent node and attribute with XPath.

var paras = html.DocumentNode.SelectNodes(
    "//p[not(descendant::p) and name(..)='div' and ../@edth_correction='N']");

foreach (var p in paras)
{
    // do work
}

To test node ancestors try this

var paragraphe = html.DocumentNode.SelectNodes(".//p[not(descendant::p)]");

for (int i = 0; i < paragraphe.Count; i++)
{
    foreach (var ancestor in paragraphe[i].Ancestors("div"))
    {
        if (ancestor.ChildAttributes("edth_correction").Any(a => a.Value == "N"))
        {
            // do work
        }
    }
}

Or with XPath

var paras = html.DocumentNode.SelectNodes(
    "//p[not(descendant::p) and ancestor::div/@edth_correction='N']");

foreach (var p in paras)
{
    // do work
}

I'm not sure about the second approach. Since I don't know your data source.

Also you can try XPath

"//p[not(descendant::p) and ancestor::*[name(.)='div' and ./@edth_correction='N']]"


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why