在groovy中对xml节点排序



我有一个XML,我需要向其中添加新节点,这是使用appendNode实现的。但是,新添加的节点放在XML的末尾。现在我想对这个XML进行排序,以便它进入正确的位置:

<Order>
<Customer>
...
</Customer>
<item>
<itemID>1</itemID>
</item>
<item>
<parentItemID>1</parentItemID>
<priority>25</priority>
</item>
<item>
<itemID>2</itemID>
</item>
<deliverydetails>
</deliverydetails>
<invoiceTerms>
....
</invoiceTerms>
//this is my newly added item
<item>
<parentItemID>2</parentItemID>
<priority>35</priority>
</item>
</Order>

我需要重新排序,使其出现在顶部,如:

<Order>
<Customer>
...
</Customer>
<item>
<itemID>1</itemID>
</item>
<item>
<parentItemID>1</parentItemID>
<priority>25</priority>
</item>
<item>
<itemID>2</itemID>
</item>
<item>
<parentItemID>2</parentItemID>
<priority>35</priority>
</item>
<deliverydetails>
</deliverydetails>
<invoiceTerms>
....
</invoiceTerms>
</Order>

尝试以下代码:

Node root = new XmlParser().parse(xml);
def orderNode = root.Order;
....
orderNode[0].children().sort(true) {it.item.parentItemID.text()}

我只需要将我新添加的最后一个项目节点与其他项目节点一起显示,而不是在末尾(最好与在parentItemID下指定的项目ID一起,以便项目及其相关子项在一起)

如果您确定itemID为2的项(您新添加的项的parentItemID)将出现在输入XML中,您可以简单地执行:

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="item[itemID=2]">
<xsl:copy-of select="."/>
<item>
<parentItemID>2</parentItemID>
<priority>35</priority>
</item>
</xsl:template>

</xsl:stylesheet>

—added—

如果您只想重新排序节点,以便所有item元素保持在一起(在新项目已经添加之后),那么您可以这样做:

<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="*"/>
<xsl:template match="/Order">
<xsl:copy>
<xsl:copy-of select="Customer"/>
<xsl:copy-of select="item"/>
<xsl:copy-of select="deliverydetails"/>
<xsl:copy-of select="invoiceTerms"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

如果您想确保新添加的项位于其父项之后(或者,更准确地说,每个子项位于其父项之后),请尝试:

<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="*"/>
<xsl:key name="sub-item" match="item" use="parentItemID" />
<xsl:template match="/Order">
<xsl:copy>
<xsl:copy-of select="Customer"/>
<xsl:for-each select="item[not(parentItemID)]">
<xsl:copy-of select="."/>
<xsl:copy-of select="key('sub-item', itemID)"/>
</xsl:for-each>
<xsl:copy-of select="deliverydetails"/>
<xsl:copy-of select="invoiceTerms"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

最新更新