【问题标题】:Select elements if a particular sibling is present with a particular child node如果特定兄弟节点与特定子节点一起存在,则选择元素
【发布时间】:2015-04-23 17:02:23
【问题描述】:

我正在尝试选择具有下一个兄弟节点 dict 并且其中一个子节点为 true 的所有键,例如在下面的 xml 中:

<dict>
    <key>A</key>
    <dict>
        <key>Disabled</key>
        <true/>
    </dict>
    <key>B</key>
    <dict>
        <key>Disabled</key>
        <false/>
    </dict>
    <key>C</key>
    <dict>
        <key>Disabled</key>
        <true/>
    </dict>
    <key>D</key>
    <id>1</id>
</dict>

我应该得到 A 和 C。我试过了:

//key[../dict/true]
//key[../dict/[following-sibling::dict/true]]

还有很多其他的。任何帮助将不胜感激。

【问题讨论】:

    标签: xml xpath


    【解决方案1】:

    你需要的路径表达式是

    /dict/key[following-sibling::*[position() = 1 and name() = 'dict' and true]]
    

    翻译成

    /dict/key                Select an outermost element, and its children `key`
    [following-sibling::*    but only if there is a following sibling
    [position() = 1          that is the first following sibling
    and name() = 'dict'      and that is also a `dict` element
    and true]]               that has at least one child element named `true`.
    

    以你展示的文档为输入,结果为(个别结果以----------分隔):

    <key>A</key>
    -----------------------
    <key>C</key>
    

    或者:

    /dict/key[following-sibling::*[position() = 1 and self::dict and true]]
    

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      //key[following-sibling::dict[position()=1]/true]
      

      这会选择以下 dict 元素的 position() 为 1(意味着紧随 key 以及 true 的后代。

      following-sibling::node() 选择 ALL 以下兄弟姐妹,但 following-sibling::node()[position()=1] 仅选择 FIRST 一个。

      【讨论】:

      • 实际上,您的路径表达式还将选择key 元素,这些元素没有 有一个名为dict 的直接下一个兄弟 - 因为following-sibling::dict[position()=1] 表示“第一个@987654331 @当前上下文节点之后的元素”,而不是一般的第一个后续兄弟。
      • 不,xpath 没有返回任何结果。
      • @orange,不确定您的环境,但是对于您的 xml 示例,我的 xpath 确实返回了预期的结果。
      • @orange 不,这个表达式当然是正确的——要么你做错了,要么输入的文档不是你给我们看的。
      • 是的,查询在 nokogiri 中正常工作! wot 很少使用这些在线工具,他们找不到一个好的开源标准兼容 xpath 库来使用??如果你们不来救援,我本可以轻松地再花几个小时把头发拔掉:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      相关资源
      最近更新 更多