Jason
Jason

Reputation: 3689

Concatenate values of multiple xml elements into single element using xslt

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>

Upvotes: 3

Views: 18957

Answers (2)

guido
guido

Reputation: 19194

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>

Upvotes: 5

Jason
Jason

Reputation: 3689

I worked it out, like this:

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

Upvotes: 1

Related Questions