anpami
anpami

Reputation: 888

XPath: Select multiple 'following-sibling'

Is it possible to have a single XPath query to select all of two tags of following-siblings?

E.g. select all tags child (id=2 and id=3) and rogue who are all siblings of child[@name = 'alpha'] in this xpath-testbed (or see the snippet below).

My failed attempts:

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

The testbed snippet is the following:

<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>

Upvotes: 0

Views: 812

Answers (1)

David Denenberg
David Denenberg

Reputation: 730

The question appears to silently assume that it is not desirable to include child id values in the XPath expression. This solution is along the lines of what you are trying:

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

The parentheses construct a sequence. The | is the union operator. Thus this is forming a sequence of all of the following sibling rogue and child elements.

Another working expression that is similar to the initial attempts in the question. This selects all following siblings, but uses a predicate to restrict to only rogue and child.

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

Upvotes: 1

Related Questions