Jonathan Römer
Jonathan Römer

Reputation: 628

XSLT combining 2 nodes into a new node

Im struggling with XML and XSLt transformations, i have the following.

<<?xml version="1.0" encoding="utf-8"?>
<playlist>
  <song>
    <title>Little Fluffy Clouds</title>
    <artist>the Orb</artist>
  </song>
</playlist>

I want to combine title and artits into a new node called: info

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <!--Identity Transform.-->
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="title | artits">
        <info>
            <xsl:value-of select="."/>
        </info>
    </xsl:template> 
</xsl:stylesheet>

The above returns:

<playlist>
  <info>Little Fluffy Clouds</info>
  <info>the Orb</info>
</playlist>
 

I need to combine these, this is supposed to be simple but i cant get it right, what i would want is:

<playlist>
  <info>Little Fluffy Clouds the Orb</info>
</playlist>

Upvotes: 0

Views: 83

Answers (1)

Linga Murthy C S
Linga Murthy C S

Reputation: 5432

You can use a template for song and use apply-templates for its children's text nodes like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<!--Identity Transform.-->
<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="song">
    <xsl:copy>
        <info>
            <xsl:apply-templates select="title/text()"/>
            <xsl:text> </xsl:text>
            <xsl:apply-templates select="artist/text()"/>
        </info>
    </xsl:copy>
</xsl:template> 
</xsl:stylesheet>

You can also use, alternatively:

<info>
    <xsl:value-of select="concat(title,' ',artist)"/>
</info>

Upvotes: 1

Related Questions