My goal is to sort XML elements alphabetically. I found solution here: Sort elements of arbitrary XML document recursively
part:
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 ) )
in Groovy Web Console, it always return XML nodes in different order, not alphabetically. I cannot use XSLT transformation, this may work for any XML document
Is there any help to modify the code?