这是上下文:我使用htmlagilitypack选择这样的p节点:
var paragraphe = html.DocumentNode.SelectNodes(".//p[not(descendant::p)]");
然后使用for循环,我想每次测试,如果此DOM元素的母体是DIV的,并且包含一个特定属性,例如:div[@edth_correction='N']
但是我不知道如何获取父节点,我已经编写了我必须做的工作的所有代码。
我知道我可以做这样的事情: paragraphe[i].ParentNode.Attributes.Equals()
,但我不知道该在这个平等上写什么,如果这是我必须使用的情况。
尝试这种方式
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
}
}
另一种方式:使用XPath检查父节点和属性。
var paras = html.DocumentNode.SelectNodes(
"//p[not(descendant::p) and name(..)='div' and ../@edth_correction='N']");
foreach (var p in paras)
{
// do work
}
测试节点祖先尝试此
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
}
}
}
或xpath
var paras = html.DocumentNode.SelectNodes(
"//p[not(descendant::p) and ancestor::div/@edth_correction='N']");
foreach (var p in paras)
{
// do work
}
我不确定第二种方法。由于我不知道您的数据源。
您也可以尝试XPath
"//p[not(descendant::p) and ancestor::*[name(.)='div' and ./@edth_correction='N']]"