1

2

XPATH query: How to get two items?

My HTML code is:

<table> <tr> <td class="data1"><p>1</td></td> <td class="data1"><p>2</td></td> <td class="data1"><p>3</td></td> <td class="data1"><p>4</td></td> </tr> <tr> <td class="data1"><p>5</td></td> <td class="data1"><p>6</td></td> <td class="data1"><p>7</td></td> <td class="data1"><p>8</td></td> </tr> </table> 

My request:

 xpath='//tr//td[@class="data1"][4]/p' 

Results:

 <p>4</p> <p>8</p> 

The results are correct ! but if I want to get an example:

 <p>3</p> <p>4</p> <p>7</p> <p>8</p> 

So

[3] / p and [4] / p

How to get these two elements each <tr> ?

Thank you very much!

+6
xpath
source share
2 answers

I think you can look for something like

 [position() > 2] 

which retrieves all the elements after the first two.

+6
source share

First of all, note that the XML provided is not correct!

I assume that the finished XML-XML, built on the right basis, looks something like this:

 <table> <tr> <td class="data1"><p>1</p></td> <td class="data1"><p>2</p></td> <td class="data1"><p>3</p></td> <td class="data1"><p>4</p></td> </tr> <tr> <td class="data1"><p>5</p></td> <td class="data1"><p>6</p></td> <td class="data1"><p>7</p></td> <td class="data1"><p>8</p></td> </tr> </table> 

This XML document provides my answers.

Using

/*/*/td[position() = 3 or position() = 4]/p

Or you can use the XPath join operator :

/*/*/td[3]/p | /*/*/td[4]/p

The following is incorrect :

/*/*/td[3] [4]/p

This indicates the choice of the 4th node /*/*/td[3] , but will not select anything , because /*/*/td[3] selects only two nodes.

Finally, here is the transformation that, when launched, shows the result of all XPath expressions above :

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <xsl:copy-of select=" /*/*/td[position() = 3 or position() = 4]/p"/> ---------------------- <xsl:copy-of select=" /*/*/td[3]/p | /*/*/td[4]/p"/> ---------------------- <xsl:copy-of select=" /*/*/td[3][4]/p"/> </xsl:template> </xsl:stylesheet> 
+4
source share

All Articles