Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate values of multiple xml elements into single element using xslt

Tags:

xml

xslt

xslt-1.0

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>
like image 426
Jason Avatar asked Dec 13 '25 17:12

Jason


2 Answers

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>
like image 175
guido Avatar answered Dec 15 '25 19:12

guido


I worked it out, like this:

<xsl:value-of select="concat(., ../field[@name = 'Address2'], ../field[@name = 'Address3'])"/>
like image 32
Jason Avatar answered Dec 15 '25 17:12

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!