Transform two nodes into one using xslt

2019-07-05 05:01发布

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.

标签: xml xslt
2条回答
ゆ 、 Hurt°
2楼-- · 2019-07-05 05:31

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>
查看更多
在下西门庆
3楼-- · 2019-07-05 05:39

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>
查看更多
登录 后发表回答