I have a HTML/XML document similar to the following. There can be one or more ‘tr’ of the same colour before switching to the other colour in an arbitrarily repeating pattern. This is an example:
<tr class='red'></tr>
<tr class='blue'></tr>
<tr class='red'></tr>
<tr class='red'></tr>
<tr class='red'></tr>
<tr class='blue'></tr>
<tr class='blue'></tr>
<tr class='red'></tr>
<tr class='red'></tr>
<tr class='blue'></tr>
What I am looking for is an XPath (1.0) expression which, starting from the first ‘tr’ in any colour ‘block’ (note that there is no markup indicating these blocks, only alterations in the colour), selects the following subsequent ‘tr’s within that block only.
I have tried the following expression
./following-sibling::tr[@class=preceding-sibling::tr[1]/@class]
but this also selects the second+ ‘tr’s of subsequent blocks. I feel like I’m close to what I need, but can’t quite manage it.
Thanks in advance.
Edit: The desired output is a nodeset containing the subsequent ‘tr’s within the block (and only that block).
This XPath 1.0 expression selects the first “block” of blue
trelements:Explanation:
Using the wellknown Kayessian formula for node-set intersection:
This XPath expression selects exactly the nodes that belong to both the node-set
$ns1and the node-set$ns2.In this particular case we simply substitute
$ns1and$ns2with their appropriate specific XPath expressions — one is the first bluetrand all of its following siblings, the other is the first non-bluetrfollowing the first bluetrand all of its preceding siblings. The intersection of these two node-sets is exactly the wanted first block of bluetrs.XSLT – based verification:
when this transformation is applied on the following XML document:
the XPath expression is evaluated and the selected nodes are copied to the output: