XSLT XML排序 - 缺少根属性

时间:2017-02-06 03:44:32

标签: xml xslt

我有一个需要排序的xml文档。我有这个工作.. 但是排序后的根元素缺少属性 我尝试了MS Forum post但没有用。我想要我的根节点属性。谢谢

输入XML然后XSLT

<?xml version="1.0" encoding="UTF-8"?>
<TestProduct ProductName="SCADA" MaxResults="20" SamplesUsed="5">
  <TestCollection TestName="TestABC" Expected="Passed" Status="STABLE">
    <TestInfo TestResult="Passed" Version="8.0.1.19" Time="" Duration="" />
    <TestInfo TestResult="Passed" Version="8.0.1.18" Time="" Duration="" />
  </TestCollection>
  <!-- Lots of TestCollection's -->
  </TestProduct>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="TestProduct">
        <xsl:copy>
            <xsl:for-each select="TestCollection">
                <xsl:sort select="@TestName" order="ascending"/>
                <xsl:copy-of select="."/>
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

1 个答案:

答案 0 :(得分:1)

您缺少复制TestProduct元素的属性。 将<xsl:copy-of select="@*"/>添加为<xsl:copy>的第一个孩子即可。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="TestProduct">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:for-each select="TestCollection">
                <xsl:sort select="@TestName" order="ascending"/>
                <xsl:copy-of select="."/>
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

XSLT下面有一个Identity Transform Template,可以按原样复制节点。这是我喜欢的方式:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="TestProduct">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates select="TestCollection">
                <xsl:sort select="@TestName" order="ascending"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

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

</xsl:stylesheet>