...">

Convert two nodes to one using 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 for the 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 with XSLT? Also, pay attention to the new node called <combined>.

I welcome your help.

Thank.

+3
source share
2 answers

You can use this template to convert parent-with-child to a merged element:

<xsl:template match="parent">
   <combined>
      <xsl:copy-of select="@* | child/@*" />
   </combined>
</xsl:template>

What this means is, copy all the attributes from the input element <parent>and it <child>to the output element <combined>.

You will also need an identification template to pass the element <data>and other nodes through:

<xsl:template match="node() | @*">
   <xsl:copy>
      <xsl:apply-templates select="node() | @*" />
   </xsl:copy>
</xsl:template>
+3
source

, ?

Straightforwad:

   <xsl:template match="combined">
       <parent>
          <xsl:copy-of select="@Id|@Value"/>
          <child x="{@x}" y="{@y}"/>
       </parent>
    </xsl:template>
+3

All Articles