Sort XML in Groovy

I looked at the documentation for sorting XML using Groovy

def records = new XmlParser().parseText(XmlExamples.CAR_RECORDS)
assert ['Royale', 'P50', 'HSV Maloo'] == records.car.sort{ it.'@year'.toInteger() }.'@name'

but what I'm trying to do is sort the XML and then return the sorted xml string. I know that I can completely rebuild XML after sorting is complete.

I know that I can run XML conversion to XML to sort it

def factory = TransformerFactory.newInstance()
def transformer = factory.newTransformer(new StreamSource(new StringReader(xslt)))
transformer.transform(new StreamSource(new StringReader(input)), new StreamResult(System.out))

BUT I was looking for Groovy magic to facilitate me

+3
source share
1 answer

The solution is to directly replace the list carwithin records. Not sure if magic still exists!

records.value = records.car.sort{ it.'@year'.toInteger() }
println XmlUtil.serialize(records)
+4
source

Source: https://habr.com/ru/post/1761353/


All Articles