9
votes

I would like to use XPath to extract all the text from all the <li> elements, that are in the specialList list and return one string separated by spaces or commas. Is this possible?

Lets say the DOM includes the following HTML:

<ul class="specialList">
   <li>one</li>
   <li>two</li>
   <li>three</li>
   <li>four</li>
</ul>

Desired Output

one, two, three, four

OR

one two three four
2

2 Answers

10
votes

In XPath 1.0, this is only possible if you know the number of elements in advance using concat(...):

concat(//li[1], ', ', //li[2], ', ', //li[3], ', ', //li[4])

If you're lucky, you can just return all result strings for //li/text() and set the output parameters of your XPath processor to concatenate them like you want. This depends on the processor, so there is no general solution and this is no way to go if you want to further process the results within XPath.

In XPath 2.0, you can use fn:string-join($sequence, $delemiter) for input of arbitrary length:

fn:string-join(//li, ', ')
1
votes

Though this possible using XSLT 1.0

<xsl:for-each select="ul/li">
   <xsl:value-of select="."/>
   <xsl:if test="position() != last()">
       <xsl:text>,</xsl:text>
   </xsl:if>
</xsl:for-each>