Sort XML elements in predetermined order using XSLT

后端 未结 1 795
猫巷女王i
猫巷女王i 2021-01-27 05:49

I have to following XML:

 
       
       
       
       
       

        
相关标签:
1条回答
  • 2021-01-27 06:10

    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>
    
    0 讨论(0)
提交回复
热议问题