Lenka
Lenka

Reputation: 75

How to get all the element value which have the same name

I have a requirement where I need to get all the values of the elements called ID, concatenate them and display. I've the solution with me now. Wouldn't there be a better way to get the values?

Input:

<Response>
    <Error/>
    <Data>
        <Account>
            <IDs>
                <ID>386</ID>
                <ID>287</ID>
                <ID>997</ID>
                <ID>2709</ID>
            </IDs>
        </Account>
    </Data>
</Response>

Hard coded XSL:

<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="concat(//Account/IDs/ID[1]/text(),'$',//Account/IDs/ID[2]/text(),'$',//Account/IDs/ID[3]/text(),'$',//Account/IDs/ID[4]/text() )"/>
    </xsl:template>
</xsl:stylesheet>

Output:

386$287$997$2709

Dynamic XSL:

<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:strip-space elements="*"/> 
    <xsl:template match="ID">
        <xsl:value-of select="concat(., '$')"/>
    </xsl:template>        
    <xsl:template match="text()"/>
</xsl:stylesheet>

Which gives the same output as above:

386$287$997$2709$

So both works for me. But what I was thinking that, is there a way where I can set the XPATH dynamically in the Hard coded XSL, so that it picks up all the value of ID, instead of mentioning 1, 2, 3, 4 and so on.

Upvotes: 0

Views: 560

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167571

In XSLT 2 and 3 you can do it directly with pure XPath, as Tim has already pointed out using the function string-join, string-join(//Account/IDs/ID, '$'), but you can as well rely on xsl:value-of and <xsl:value-of select="//Account/IDs/ID" separator="$"/>.

Upvotes: 1

Related Questions