1

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?

Community
  • 1
  • 1

2 Answers2

1

You can sort elements by putting them in a list

List items = []
rss.channel.item.each {
   items << it
}

items.sort {a,b -> a.title.text()) <=> b.title.text())}

This will give you the elements sorted by title

Mark Sholund
  • 1,273
  • 2
  • 18
  • 32
0

Attributes are stored as a HashMap, therefore have no order

They don't have an order in XML either

So I don't think you can sort them

tim_yates
  • 167,322
  • 27
  • 342
  • 338