简体   繁体   中英

How to sort an xml file by attribute value in xslt?

I want to sort an xml file by the attribute value "class" of the element "entity". In output I want to keep the same structure of my input xml, Here a part of my xml code:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
    version="1.0">
<entity class="entityZ" metadata-complete="false">
<table name="F_ENTITYZ">
<unique-constraint>
<column-name>column1</column-name>
</unique-constraint>
<unique-constraint>
<column-name>column2</column-name>
</unique-constraint>
</table>
<sequence-generator name="SEQUENCEZ_" sequence-name="F_SEQUENCEZ_" allocation-size="1" initial-value="1"/>
<attributes>
</attributes>
</entity>
<entity class="entityA" metadata-complete="false">
<table name="F_ENTITYA">
<unique-constraint>
<column-name>column1</column-name>
</unique-constraint>
</table>
<sequence-generator name="SEQUENCEA_" sequence-name="F_SEQUENCEA_" allocation-size="1" initial-value="1"/>
<attributes>
</attributes>
<post-persist method-name="traceHistory"/>
<post-update method-name="traceHistory"/>
</entity>
<entity class="entityB" metadata-complete="false">
<table name="F_ENTITYB">
<unique-constraint>
<column-name>column1</column-name>
</unique-constraint>
</table>
<sequence-generator name="SEQUENCEB_" sequence-name="F_SEQUENCEB_" allocation-size="1" initial-value="1"/>
<attributes>
</attributes>
</entity>
</entity-mappings>

Waiting for your help ...

With xslt you can do this:

<xsl:template match="/">
    <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
version="1.0">

        <xsl:for-each select="*/*">
            <xsl:sort select="@class" />
            <xsl:copy-of select="." />
        </xsl:for-each>

    </entity-mappings>
</xsl:template>

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