Grails Cookbook - A collection of tutorials and examples

Groovy Sort Information in XML Document

Given an XML, we can modify it's contents by sorting the entries based on some criteria. Below is a simple code example on how to do that.

Below is an XML document that contains a list of person. We then sort the persons by their age. We do this by parsing the XML document using XmlParser, sort the information using closure, and create the XML representation of the sorted objects. Below is the code that does that:

package test
import groovy.xml.MarkupBuilder
/**
 * A simple example that sorts the result of parsed XML.
 */
class Test {
    static stringXML = 
        '<personDatabase>'+
            '  <person><firstName>John</firstName><lastName>Doe</lastName><age>25</age></person>'+
            '  <person><firstName>Jane</firstName><lastName>Smith</lastName><age>31</age></person>'+
            '  <person><firstName>Robert</firstName><lastName>Doe</lastName><age>11</age></person>'+
            '  <person><firstName>Michael</firstName><lastName>Smith</lastName><age>55</age></person>'+
            '  <person><firstName>Scott</firstName><lastName>Williams</lastName><age>35</age></person>'+
            '  <person><firstName>Alice</firstName><lastName>Anthony</lastName><age>14</age></person>'+
        '</personDatabase>'
    static main(args) {
        def people = new XmlParser().parseText(stringXML)
        people.value = people.person.sort { p ->
            p.age[0].text().toInteger()
        }
        def stringWriter = new StringWriter()
        new XmlNodePrinter(new PrintWriter(stringWriter)).print(people)
        def newXml = stringWriter.toString()
        println newXml
    }
}
As shown above, we can use closure to do the filtering. We get the value of a person's age and convert it to numeric value. We then use a XmlNodePrinter to store it back as XML. The result is below which shows the XML with person sorted by age:
<personDatabase>
  <person>
    <firstName>
      Robert
    </firstName>
    <lastName>
      Doe
    </lastName>
    <age>
      11
    </age>
  </person>
  <person>
    <firstName>
      Alice
    </firstName>
    <lastName>
      Anthony
    </lastName>
    <age>
      14
    </age>
  </person>
  <person>
    <firstName>
      John
    </firstName>
    <lastName>
      Doe
    </lastName>
    <age>
      25
    </age>
  </person>
  <person>
    <firstName>
      Jane
    </firstName>
    <lastName>
      Smith
    </lastName>
    <age>
      31
    </age>
  </person>
  <person>
    <firstName>
      Scott
    </firstName>
    <lastName>
      Williams
    </lastName>
    <age>
      35
    </age>
  </person>
  <person>
    <firstName>
      Michael
    </firstName>
    <lastName>
      Smith
    </lastName>
    <age>
      55
    </age>
  </person>
</personDatabase>
Posts about XML