将元素移动到父级

时间:2017-04-29 23:52:40

标签: xslt-1.0

我是XSLT的新手,我想将一个包含其所有子元素的元素移动到根目录,如下所述:

输入XML

<a name = "test">
  <b name = "test1">
    <c name = "test2">
        <c1>Dummy</c1>
    </c>
 </b>
</a>

预期:

<a name = "test">
  <b name = "test1">        
  </b>
  <c name = "test2">
    <c1>Dummy</c1>
  </c>
</a>

1 个答案:

答案 0 :(得分:1)

试试这个。 (这称为推送编程。)

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxml="urn:schemas-microsoft-com:xslt">

<xsl:output method="xml" omit-xml-declaration="yes" version="1.0" encoding="UTF-8" />


  <xsl:template match="a">
    <xsl:copy>
      <xsl:apply-templates select="@*|b"/>
      <xsl:apply-templates select="b/c"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="b">
    <xsl:copy>
      <!-- Don't do an apply template with c in it. Just get the attributes for b. The c node pushed from the a template gets handled by the identity. -->
      <xsl:apply-templates select="@*"/>
    </xsl:copy>
  </xsl:template>

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

</xsl:stylesheet>