我有一个带有命名空间的XmlDocument,我需要找到具有特定属性的元素的特定子节点。我可以得到父母,我可以得到所有的孩子,但我找不到xpath表达式来获取我想要的元素(img)。我可以通过孩子们找到img元素,但我真的很想用一个xpath表达式找到它。
第一个SelectNodes为我提供了跨度的所有孩子,其中class =' distinct'。我只想要img元素。第二个选择返回0个节点。
如果表达式或xml中不存在命名空间,则第二个选择将返回img元素。
XML:
<p xmlns="blorf">
<span class="distinct" >
<img alt="" src="eq_54.png"/>
<span class="other-span">
<inner xmlns="scrubs">
<x1/>
</inner>
</span>
</span>
</p>
代码:
...
doc.LoadXml(_xml);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("a", "blorf");
XmlNodeList list = doc.SelectNodes("//a:span[@class='distinct']/*",nsmgr);
Console.WriteLine("count is " + list.Count);
list = doc.SelectNodes("//a:span[@class='distinct']/img", nsmgr);
Console.WriteLine("count is " + list.Count);
答案 0 :(得分:1)
使用list = doc.SelectNodes("//a:span[@class='distinct']/a:img", nsmgr);
,您将返回img
节点。