简体   繁体   中英

How to sort specific XML element's group with XSLT?

How do I sort a group of elements within a node of the XML file.

Here is my input

<Root>
    <Level_1.1>...</Level_1.1>
    <Level_1.2>...</Level_1.2>
    <Level_1.3>
        <Sub.1>...</Sub.1>
        <Sub.2>
            <S.1>1</S.1>
            <S.3>Something</S.3>
            <S.6>C</S.6>
            <S.2/>
            <S.4>
                <AA.1>2</AA.1>
            </S.4>
            <S.5/>
        </Sub.2>
        <Sub.3>...</Sub.3>
    </Level_1.3>
    <Level_1.4>...</Level_1.4>
</Root>

Would like to have output to the same hierarchy location as below.

<Root>
    <Level_1.1>...</Level_1.1>
    <Level_1.2>...</Level_1.2>
    <Level_1.3>
        <Sub.2>
            <S.1>1</S.1>
            <S.2/>
            <S.3>Something</S.3>
            <S.4><AA.1>2</AA.1></S.4>
            <S.5/>
            <S.6>C</S.6>
        </Sub.2>
        <Sub.3>...</Sub.3>
    </Level_1.3>
    <Level_1.4>...</Level_1.4>
</Root>

This is what I have tried as to other's suggestion but it's not working.

<xsl:template match="/Root/Level_1.3">
<xsl:copy>
    <xsl:apply-templates>
        <xsl:sort select="Sub.2" order="ascending"/>
    </xsl:apply-templates>
</xsl:copy>

Try it this way?

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="Sub.2">
    <xsl:copy>
        <xsl:apply-templates>
            <xsl:sort select="name()" data-type="text" order="ascending"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM