user1677271
user1677271

Reputation: 67

Split xml complex node elements into multiple nodes using xslt

Is there a way to split a parent node into multiple nodes using xslt?

I want to transform the source xml into destination.

Source xml

    <?xml version="1.0" encoding="utf-8"?>
    <rss version="2.0">
        <channel>
            <item>
                <id>Some id</id>
                <node1>
                    <node2 size="10.5" code="abcd"></node2>
                    <node2 size="10" code="cdef"></node2>        
                </node1>
            </item>
        </channel>
    </rss>

Destination xml

    <?xml version="1.0" encoding="utf-8"?>
    <rss version="2.0">
        <channel>
            <item>
                <id>Some id_10.5</id>
                <size>10.5</size>
                <code>abcd</code>
            </item>
            <item>
                <id>Some id_10</id>
                <size>10</size>
                <code>cdef</code>
            </item>
        </channel>
    </rss>

If you notice the value of node id in destination xml, it has an underscore and size appended to it.

Upvotes: 1

Views: 1196

Answers (1)

Michael Kay
Michael Kay

Reputation: 163587

Very straightforward, it's not clear why you are finding it difficult.

<xsl:template match="node2">
            <item>
                <id><xsl:value-of select="../../id"/>_<xsl:value-of select="@size"/></id>
                <size><xsl:value-of select="@size"/></size>
                <code><xsl:value-of select="@code"/></code>
            </item> 
</xsl:template> 

plus some trivial template rules for other elements.

Upvotes: 0

Related Questions