使用XSLT按预定顺序对XML元素进行排序 [英] Sort XML elements in predetermined order using XSLT

查看:88
本文介绍了使用XSLT按预定顺序对XML元素进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须遵循XML:

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

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

The order of a, b and c elements is random. Now I want to sort the elements in a predefined way (first b, then a, then c).

我尝试了以下xslt:

I tried the following 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进行排序.

Which sorts the element by name, thus a,b,c as expected.

除了降序还是升序之外,是否有办法定义排序的顺序?

Is there a way to define the order of the sort other then descending/ascending?

谢谢!

推荐答案

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

Now I want to sort the elements in a predefined way (first b, then a, then 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>

这篇关于使用XSLT按预定顺序对XML元素进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆