如何通过xslt中的属性值对xml文件进行排序?

时间:2018-10-09 08:05:01

标签: xml xslt

我想按元素“实体”的属性值“类”对xml文件进行排序。在输出中,我想保持输入xml的相同结构, 这是我的xml代码的一部分:

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

正在等待您的帮助...

1 个答案:

答案 0 :(得分:0)

使用xslt可以执行以下操作:

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