使用 XPath 和 asp.net XmlDocument 在命名空间中查找特定子节点

Finding specific child node in namespace with XPath and asp.net XmlDocument

我有一个带有命名空间的 XmlDocument,我需要找到一个具有特定属性的元素的特定子元素。我可以获得父项,也可以获得所有子项,但是我找不到一个 xpath 表达式来获取我想要的元素 (img)。我可以遍历子项并找到 img 元素,但我真的很想只用一个 xpath 表达式找到它。

第一个 SelectNodes 为我提供了 class='distinct' 范围内的所有子节点。我只想要 img 元素。第二个selectreturns 0个节点。

如果命名空间不存在于表达式或 xml 中,第二个 select 将 return 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);

使用list = doc.SelectNodes("//a:span[@class='distinct']/a:img", nsmgr);,您将取回img节点。

this answer

中的一些解释