Concatenate values of multiple xml elements into single element using xslt

16,662

Solution 1

You can make it a little more generic like this (given the parent of field elements is fields):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="fields">
    <field>
        <xsl:attribute name="name">Address</xsl:attribute>
        <xsl:apply-templates select="node()"/>
    </field>
</xsl:template>
<xsl:template match="field[starts-with(@name, 'Address')]">
    <xsl:value-of select="concat(.,'\r\n')"/></xsl:template>
</xsl:stylesheet>

Solution 2

I worked it out, like this:

<xsl:value-of select="concat(., ../field[@name = 'Address2'], ../field[@name = 'Address3'])"/>
Share:
16,662
Jason
Author by

Jason

Updated on June 27, 2022

Comments

  • Jason
    Jason almost 2 years

    My source xml file has elements in this form:

    <field name="Address1">Address1Value</field>
    <field name="Address2">Address2Value</field>
    <field name="Address3">Address3Value</field>
    

    I need to merge these into a single element, thus:

    <field name="Address">Address1Value\r\nAddress2Value\r\nAddress3Value</field>
    

    I know how to get the value of the Address1 element (as below), I just can't figure out how to augment it with the other two. How can I do this?

    <xsl:template match="field[@name = 'Address1']">
        <field>
            <xsl:attribute name="name">Address</xsl:attribute>
            <xsl:value-of select="concat(., 'how-do-I-get-the-values-of-Address2-and-Address-here3?')"/>
        </field>
    </xsl:template>