【问题标题】:How to: seaching XML child nodes如何:搜索 XML 子节点
【发布时间】:2009-04-06 14:05:10
【问题描述】:

给定一个 Xml 如下所示。我将如何编写 XPATH 查询来获取“key”值具有特定值(比如 2)的“leaf2”子项的值

我正在使用 C# .NET。目前,我只是在寻找使用 SelectNodes 获取密钥的 Xpath,找到正确的值然后导航回 leaf2。

<root>
    <child>
        <anotherChild>
           <key>1</key>
        </anotherChild>
        <leaf1>X</leaf1>
        <leaf2>Y</leaf2>
        <leaf3></leaf3>
    </child>
    <child>
        <anotherChild>
           <key>2</key>
        </anotherChild>
        <leaf1>A</leaf1>
        <leaf2>B</leaf2>
        <leaf3></leaf3>
    </child>
</root>

【问题讨论】:

    标签: c# xml xpath


    【解决方案1】:

    你想要:

    /root/child[anotherChild/key = '2']/leaf2
    

    这就是说,“获取名为leaf2 的元素,其父元素为child,其祖父元素为root,其中child 被其名为anotherChild 的子元素与名为key 的子元素过滤其值为2。”

    【讨论】:

      【解决方案2】:

      或者,也许更灵活一点,因为它不假设祖父是 root

      //child/anotherChild/key[text()="2"]/../../leaf2
      

      "找到带有文本2的key,parent anotherChild和grandparentchild,去grandparent(即child,然后找到leaf2"

      【讨论】:

      • 应该这样做。我在 SketchPath 中针对您的 XML 进行了测试(所以实际上不是在 C# 中)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      相关资源
      最近更新 更多