Sorting XML nodes
Sometimes it is important to preserve XML data in certain order. Ordered data is easier to read and search, and some computer systems may require data they consume to be sorted. One of the most basic requirements that arise when dealing with XML is being able to sort nodes either by node value or attribute value. In this recipe, we are going to go through a couple of ways of achieving this with Groovy.
How to do it...
For this recipe, we will reuse the same XML document defined in the Searching in XML with GPath recipe.
The grooviest way to sort nodes is to replace the entire element tree with a sorted one:
import groovy.xml.XmlUtil def groovyMoviez = ''' <?xml version="1.0" encoding="UTF-8"?> ... ''' def movieList = new XmlParser().parseText(groovyMoviez) movieList.value = movieList.movie.sort { it.title.text() } println XmlUtil.serialize(movieList)
This will yield:
<?xml version="1.0" encoding="UTF-8"?> <movie-result>...