Sorting XML in Groovy
I have looked at the documentation on sorting XML with Groovy
def records = new XmlParser().parseText(XmlExamples.CAR_RECORDS)
assert ['Royale', 'P50', 'HSV Maloo'] == records.car.sort{ it.'@year'.toInteger() }.'@name'
but what I am trying to do is sort the XML and then return the xml string sorted. I know I can completely rebuil开发者_Python百科d the XML after i am done sorting.
I know I can run an XML Transformation on the XML to get it sorted
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 some Groovy magic to make it easier for me
A solution is to replace directly the list of car
within the records
. Not sure if more magic exists!
records.value = records.car.sort{ it.'@year'.toInteger() }
println XmlUtil.serialize(records)
精彩评论