【问题标题】:XSLT XML Sort - Missing Root AttributesXSLT XML 排序 - 缺少根属性
【发布时间】:2017-02-06 03:44:31
【问题描述】:

我有一个需要排序的 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>

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    您缺少TestProduct 元素的复制属性。 添加&lt;xsl:copy-of select="@*"/&gt; 作为&lt;xsl:copy&gt; 的第一个孩子就可以了。

    <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 下面有一个身份转换模板,可以照原样复制节点。这是我喜欢的方式:

    <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>
    

    【讨论】:

    • 感谢您的快速响应,它有效!任何阻止这种情况的方法都会影响输出不影响的 "
    • 我认为您的意思是缩进输出 XML。请查看我的编辑以添加&lt;xsl:output method="xml" indent="yes"/&gt;
    猜你喜欢
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    相关资源
    最近更新 更多