I have the following example document:
<root>
<p class="b">A</p>
<p class="b">B</p>
<p class="a">C</p>
<p class="a">D</p>
<p class="b">E</p>
<x>
<p class="b">F</p>
</x>
</root>
I am looking for an xpath expression which selects all direct siblings of a given node with matching class attributes, not any sibling. In above example, the first two <p class="b">
A-B should be selected; likewise the two <p class="a">
C-D, likewise the fifth single <p class="b">
E as it has no direct siblings; likewise the single <p class="b">
F inside of <x>
. Note that in this context B and C are not direct siblings because they have different class attribute valued!
What I have is this:
xml.xpath("//p") # This selects all six <p> elements.
xml.xpath("//p[@class='b']") # This selects all four <p class="b"> elements.
xml.xpath("//p/following-sibling::p[@class='b']") # This selects all <p class="b"> sibling elements, even though not direct siblings.
The last expression selects the fifth sibling as well, although there are non-matching siblings inbetween.
How do I select only direct siblings with the same class
value?
Edit To clarify: note how the last two are individual selections, not siblings!
Edit I have saved an example here. The Xpath expression based on /root/p[1]
is supposed to select A, B, C, D
.
` ?
– Jens Oct 18 '13 at 22:05` elements) separating the two, i.e. they are of different groups.
– Jens Oct 19 '13 at 12:03