gishman
gishman

Reputation: 17

xslt concatenate fields add back

Firstly, I am not good with XSLT. Can someone help me with this?

How do I concatenate two fields in a node and then add it as a new field to the original? Ex.

<Contacts>
 <Contact>
  <fName>Mickey</fName>
  <lName>Mouse</lName>
 </Contact>
<Contact>
 <fName>Daisy</fName>
 <lName>Duck</lName>
</Contact>
</Contacts>

to

<Contacts>
  <Contact>
   <fName>Mickey</fName>
   <lName>Mouse</lName>
   <fullName>MickeyMouse</fullName>
 </Contact>
 <Contact>
  <fName>Daisy</fName>
  <lName>Duck</lName>
  <fullName>DaisyDuck</fullName>
  </Contact>
 </Contacts>

thanks in advance,

Upvotes: 0

Views: 50

Answers (2)

Mats Kindahl
Mats Kindahl

Reputation: 2075

You create a template to match the Contact, like this:

<xsl:template match="Contact">
  <Contact>
    <xsl:copy-of select="*"/>
    <fullName><xsl:value-of select="concat(fName, ' ',lName)"/></fullName>
  </Contact>
</xsl:template>

Upvotes: 0

harpo
harpo

Reputation: 43208

You want a copy-with-variation. This is done idiomatically in XSLT by starting with an identity template, which copies the nodes exactly, then overriding it where you want a variation.

The following transform

<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes" />

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Contact">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
            <fullName><xsl:value-of select="concat(fName, lName)"/></fullName>
        </xsl:copy>
    </xsl:template>

</xsl:transform>

Applied to your input, gives the wanted result:

<Contacts>
    <Contact>
        <fName>Mickey</fName>
        <lName>Mouse</lName>
    <fullName>MickeyMouse</fullName></Contact>
    <Contact>
        <fName>Daisy</fName>
        <lName>Duck</lName>
    <fullName>DaisyDuck</fullName></Contact>
</Contacts>

Hope this helps.

Upvotes: 1

Related Questions