【问题标题】:XPath: Select multiple 'following-sibling'XPath:选择多个'following-sibling'
【发布时间】:2021-07-13 07:05:37
【问题描述】:

是否可以使用单个 XPath 查询来选择所有两个标签的以下兄弟姐妹?

例如在this xpath-testbed 中选择所有child[@name = 'alpha'] 的兄弟姐妹child(id=2 和id=3)和rogue(或参见下面的sn-p)。

我的失败尝试:

//child[@name = 'alpha']//following-sibling::[child|rogue]
//child[@name = 'alpha']//*[following-sibling::child or following-sibling::rogue]

测试台sn-p如下:

<parent name="data" >
   <child id="1"  name="alpha" >Some Text</child>
   <child id="2"  name="beta" >
      <grandchild id="2.1"  name="beta-alpha" ></grandchild>
      <grandchild id="2.2"  name="beta-beta" ></grandchild>
   </child>
   <pet name="tigger"  type="cat" >
      <data>
         <birthday month="sept"  day="19" ></birthday>
         <food name="Acme Cat Food" ></food>
      </data>
   </pet>
   <pet name="Fido"  type="dog" >
      <description>
         Large dog!
      </description>
      <data>
         <birthday month="feb"  day="3" ></birthday>
         <food name="Acme Dog Food" ></food>
      </data>
   </pet>
   <rogue name="is this real?" >
      <data>
         Hates dogs!
      </data>
   </rogue>
   <child id="3"  name="gamma"  mark="yes" >
      <!-- A comment -->
      <description>
         Likes all animals - especially dogs!
      </description>
      <grandchild id="3.1"  name="gamma-alpha" >
         <[CDATA[ Some non-parsable character data ]]>
      </grandchild>
      <grandchild id="3.2"  name="gamma-beta" ></grandchild>
   </child>
</parent>

【问题讨论】:

    标签: xpath


    【解决方案1】:

    这个问题似乎默默地假设在 XPath 表达式中包含 child id 值是不可取的。该解决方案与您正在尝试的方式一致:

    //child[@name = 'alpha']/(following-sibling::rogue | following-sibling::child)
    

    括号构成一个序列。 | 是联合运算符。因此,这形成了以下所有兄弟流氓和子元素的序列。

    另一个类似于问题中最初尝试的工作表达式。这会选择所有后续的兄弟姐妹,但使用谓词来限制只有 rogue 和 child。

    //child[@name = 'alpha']/following-sibling::*[self::rogue | self::child]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 2012-02-13
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多