[英]Groovy - sorting XML elements
我的目標是按字母順序對 XML 元素進行排序。 我在這里找到了解決方案: 遞歸地對任意 XML 文檔的元素進行排序
部分:
def x = '''<foo b="b" a="a" c="c">
<qwer>
<!-- A comment -->
<zxcv c="c" b="b">Some Text</zxcv>
<vcxz c="c" b="b"/>
</qwer>
<baz e="e" d="d">Woo</baz>
<bar>
<fdsa g="g" f="f"/>
<asdf g="g" f="f"/>
</bar>
</foo>'''
def order( node ) {
[ *:node.attributes() ].sort().with { attr ->
node.attributes().clear()
attr.each { node.attributes() << it }
}
node.children().sort()
.grep( Node )
.each { order( it ) }
node
}
def doc = new XmlParser().parseText( x )
println groovy.xml.XmlUtil.serialize( order( doc ) )
在 Groovy Web Console 中,它總是以不同的順序返回 XML 節點,而不是按字母順序。 我不能使用 XSLT 轉換,這可能適用於任何 XML 文檔
修改代碼有幫助嗎?
屬性存儲為 HashMap,因此沒有順序
他們也沒有 XML 格式的訂單
所以我不認為你可以對它們進行排序
您可以通過將元素放在列表中來對元素進行排序
List items = []
rss.channel.item.each {
items << it
}
items.sort {a,b -> a.title.text()) <=> b.title.text())}
這將為您提供按標題排序的元素
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.