Sort XML elements in predetermined order using XSL

2019-09-11 11:58发布

问题:

I have to following XML:

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

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

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>

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?

Thanks!

回答1:

Now I want to sort the elements in a predefined way (first b, then a, then c).

Here's one way:

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

Here's another:

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>


标签: xml sorting xslt