Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return text from several elements in one string using XPath?

Tags:

xpath

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
like image 717
AnchovyLegend Avatar asked Jun 28 '13 20:06

AnchovyLegend


Video Answer


2 Answers

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, ', ')
like image 149
Jens Erat Avatar answered Oct 04 '22 16:10

Jens Erat


Though this is 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>
like image 21
Dev Avatar answered Oct 04 '22 15:10

Dev