nereide
nereide

Reputation: 152

Add parent node to gather several children nodes using XSLT

Trying to transform that XML file:

<collection>
<collectionDetails>
    <owner>David</owner>
    <creationDate>20140515</creationDate>       
    <movie>
        <title>The Little Mermaid</title>
        <stars>5</stars>
    </movie>
    <movie>
        <title>Frozen</title>
        <stars>3</stars>
    </movie>
</collectionDetails>    

into that XML file:

<collection>
    <collectionDetails>
        <owner>David</owner>
        <creationDate>20140515</creationDate>
        <movies>
            <movie>
                <title>The Little Mermaid</title>
                <stars>5</stars>
            </movie>
            <movie>
                <title>Frozen</title>
                <stars>3</stars>
            </movie>
        </movies>
    </collectionDetails>    
</collection>

(ie) I'm just trying to add a common parent "movies" node to all "movie" nodes.

Would you have an XSLT stylesheet to accomplish that?

Upvotes: 1

Views: 689

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

Here's one way:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="collectionDetails">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()[not(self::movie)]"/>
        <movies>
            <xsl:apply-templates select="movie"/>        
        </movies>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Upvotes: 2

Related Questions