使用数据xml将Attributes转换为与parent相同的级别

时间:2018-05-10 15:54:45

标签: xml xslt

我想将子节点属性作为元素移动到父元素。对于前更改以下xml

<Parent>
 <Children>
 <Child-id Name="John Doe">52bf9104-2c5e-4f1f-a66d-552ebcc53df7</Child>
 <Child-id Name="Some One">52bf9104-2c5e-4f1f-a66d-552ebcc53daa</Child>

 </Children>
</Parent>

<Parent>

 <child-id>52bf9104-2c5e-4f1f-a66d-552ebcc53df7</child>
 <Name>John Doe</Name>
 <child-id>52bf9104-2c5e-4f1f-a66d-552ebcc53daa</child>
 <Name>John Doe</Name>
</Parent>

1 个答案:

答案 0 :(得分:0)

以下XSLT-1.0文件将XML转换为所需的状态:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

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

  <xsl:template match="Children">          <!-- Remove 'Children' element -->
    <xsl:apply-templates select="node() | @*" />
  </xsl:template>   

  <xsl:template match="Child-id">          <!-- Transform 'Child-id' element -->
    <child-id><xsl:value-of select="." /></child-id>
    <Name><xsl:value-of select="@Name" /></Name>
  </xsl:template> 

</xsl:stylesheet>

输出为:

<Parent>
    <child-id>52bf9104-2c5e-4f1f-a66d-552ebcc53df7</child-id>
    <Name>John Doe</Name>
    <child-id>52bf9104-2c5e-4f1f-a66d-552ebcc53daa</child-id>
    <Name>Some One</Name>
</Parent>