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
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, ', ')
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With