Groovy has great inbuilt xml support, and allows you to treat xml paths like objects. Reading elements and attributes is so straightforward that it was one of the factors that got me started with Groovy. So to build an object tree from xml, we just use the XmlParser
class.
To dereference an element we use normal dot syntax, for an attribute, simply add the at symbol (@) before the name, see the example below.
Groovy has another common method we have not yet discussed, findAll; which allows for finding matching items in a collection. Method findAll takes a closure that will be given each value, and returns true if the item is considered matched. In addition to using the dot operator, you can also use the square brackets notation parent[child] to retrieve xml.
We've covered quite a lot, lets have an example:
String xml = """
<dogs>
<dog type="Beagle" sound="howl"/>
<dog type="Labrador" sound="woof"/>
</dogs>"""
XmlParser parser = new XmlParser()
def dogs = parser.parseText (xml)
dogs.dog.each { dog ->
println("${dog.'@type'} sounds like ${dog.'@sound'}");
}
def dogsThatHowl = dogs.dog.findAll { dog -> dog.'@sound' == 'howl' }
dogsThatHowl.each { dog ->
println dog['@type'];
}
In the example above we read some XML that was stored in a String, that's great but its not a real word example. What if we want to read from a file or stream? Examples of both are below:
def xmldata1 = parser.parse (new FileInputStream("somefile.xml")) def xmldata2 = parser.parse (new File("~/somefilename.xml"))
I think I've covered the most important cases here, but there's much that's not covered here. For more examples see http://docs.codehaus.org/display/GROOVY/Reading+XML+using+Groovy's+XmlParser