I have the following xml input:
<data>
<parent Id="1" value="ParentOne">
<child x="1" y="2" />
</parent>
<parent Id="2" value="ParentTwo">
<child x="3" y="4" />
</parent>
</data>
What I need to output should look like this combining the parent and child nodes:
<data>
<combined Id="1" value="ParentOne" x="1" y="2" />
<combined Id="2" value="ParentTwo" x="3" y="4" />
</data>
How can I achieve this using XSLT? Also, take note of the newly named node called <combined>
.
I apreciate your help.
Thanks.
You can use this template to transform the parent-with-child into the combined element:
<xsl:template match="parent">
<combined>
<xsl:copy-of select="@* | child/@*" />
</combined>
</xsl:template>
What this does is copy all the attributes from the input <parent>
element and its <child>
, into the output <combined>
element.
You'll also want the identity template, in order to pass the <data>
element and other nodes through:
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
How would the template look like if I want to revert back to the original input structure?
Straightforwad:
<xsl:template match="combined">
<parent>
<xsl:copy-of select="@Id|@Value"/>
<child x="{@x}" y="{@y}"/>
</parent>
</xsl:template>