代码之家  ›  专栏  ›  技术社区  ›  Stefan Kendall

按名称对节点排序的XSLT?

  •  14
  • Stefan Kendall  · 技术社区  · 14 年前

    我不确定 xsl:sort 指令有效。我需要按元素的标记名(用于区分)对元素进行排序,但我似乎无法想出如何使其工作。我的第一个想法是修改identity转换并将其修改为包含一个sort语句,但我不确定如何做到这一点。

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

    1 回复  |  直到 14 年前
        1
  •  25
  •   Dimitre Novatchev    14 年前

    这种转变 :

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
     <xsl:strip-space elements="*"/>
    
     <xsl:template match="node()|@*">
      <xsl:copy>
       <xsl:apply-templates select="@*">
        <xsl:sort select="name()"/>
       </xsl:apply-templates>
    
       <xsl:apply-templates select="node()">
        <xsl:sort select="name()"/>
       </xsl:apply-templates>
      </xsl:copy>
     </xsl:template>
    </xsl:stylesheet>
    

    应用于此XML文档时 :

    <t b="x" c="y" a="t">
      <c/>
      <b/>
      <a/>
    </t>
    

    生成所需的排序输出 :

    <t a="t" b="x" c="y">
        <a></a>
        <b></b>
        <c></c>
    </t>
    

    :

    1. 不仅对元素进行排序,而且对属性进行排序 (后者依赖于实现,但可以与MSXML一起使用)。

    2. ,因为将XML文档转换为排序表示不是1:1映射。