Reputation: 3018
I have an xml file as below.
<note>
<from> </from>
<to>
<name> </name>
<number> </number>
</to>
<message>
<head> </head>
<body> </body>
</message>
</note>
I want to build xml structure like below using XSTL.
<note>
<from> </from>
<message>
<name> </name>
<number> </number>
<head> </head>
<body> </body>
</message>
</note>
I have tried something like this.
<xsl:template match="//to">
<xsl:copy-of select="//message"/>
</xsl:template>
Thanks in advance.
Upvotes: 0
Views: 416
Reputation: 70598
Start off with the Identity Template, which on its own copies nodes to the output document "as-is"
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
This means you then only have to write templates for nodes you wish to actually change.
For a start, you don't want to appearing in the same place in the output, so add a template to ignore it
<xsl:template match="to" />
Next, you want to transform the message element to append the child of the to elements to it. You do this with the following template, which is similar to the Identity Template, but with an extra line to do the extra copying.
<xsl:template match="message">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<xsl:apply-templates select="../to/*"/>
</xsl:copy>
</xsl:template>
Try this XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="to" />
<xsl:template match="message">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<xsl:apply-templates select="../to/*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Upvotes: 3