Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform two nodes into one using xslt

Tags:

xml

xslt

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.

like image 284
RynoB Avatar asked Jul 19 '26 02:07

RynoB


1 Answers

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>
like image 72
LarsH Avatar answered Jul 21 '26 16:07

LarsH