使用XSLT按预定顺序对XML元素进行排序

时间:2015-09-17 07:36:52

标签: xml sorting xslt

我必须遵循XML:

 <root>
       <a></a>
       <b></b>
       <a></a>
       <a></a>
       <b></b>
       <c></c>
</root>

a,b和c元素的顺序是随机的。 现在我想以预定义的方式对元素进行排序(首先是b,然后是a,然后是c)。

我尝试了以下xslt:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <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>

按名称对元素进行排序,因此按预期方式对a,b,c进行排序。

有没有办法定义排序顺序,然后是降序/升序?

谢谢!

1 个答案:

答案 0 :(得分:1)

  

现在我想以预定义的方式对元素进行排序(首先是b,然后是a,   然后c)。

以这种方式:

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

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

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

</xsl:stylesheet>

这是另一个:

XSLT 2.0

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

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

<xsl:template match="/root">
    <xsl:copy>
        <xsl:apply-templates select="*">
            <xsl:sort select="index-of(('b', 'a', 'c'), name())" />
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
相关问题