3

I am using XSL to convert a HTML document to XML. How to concatenate the text in all the descendant nodes of a particular type with a separator?As an example I have a table node and it has several td nodes as descendants, how to combine the text in all those td elements?For the below input and using ',' as separator, the output should be 'value1,value2,value3,value4'

<table>
    <tr>
        <td>value1</td>
    </tr>
    <tr>
        <td>
            <table>
                <tr>
                    <td>value2</td>
                    <td>value3</td>
                </tr>
                <tr>
                    <td>value4</td>
                </tr>
            </table>
        </td>
    </tr>
</table>

1 Answers1

4

Try:

<xsl:value-of select="//td[text()]" separator=","/>

or:

<xsl:value-of select="string-join(//td[text()],',')"/>

string-join() is particularly useful in AVT's.

Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
  • This should be , to concatenate only descendant tds – themanwhosoldtheworld Dec 23 '15 at 18:44
  • 1
    @themanwhosoldtheworld - It all depends on the context. You could also use `.//td` instead of `descendant::td`. – Daniel Haley Dec 23 '15 at 18:47
  • 2
    @themanwhosoldtheworld: You do realize that `.//td` is short for `descendant-or-self::td`, right? This answer is essentially correct and should be [**accepted**](http://meta.stackoverflow.com/q/5234/234215), as probably should some of the answers to the other 19 questions you've asked (yet only accepted 3). – kjhughes Dec 23 '15 at 19:12