【问题标题】:Finding specific child node in namespace with XPath and asp.net XmlDocument使用 XPath 和 asp.net XmlDocument 在命名空间中查找特定子节点
【发布时间】:2016-01-19 22:10:10
【问题描述】:

我有一个带有命名空间的 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);

【问题讨论】:

    标签: c# asp.net xpath xmldocument


    【解决方案1】:

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

    this answer中的一些解释

    【讨论】:

    • 这行得通,谢谢。所以这只是一个xpath问题,甚至不是asp.net。命名空间前缀不像默认命名空间那样“继承”——无论出于何种原因,我都期待。
    猜你喜欢
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    相关资源
    最近更新 更多