By dave | July 1, 2012

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

 

Other pages within this category

comments powered by Disqus

This site uses cookies to analyse traffic, and to record consent. We also embed Twitter, Youtube and Disqus content on some pages, these companies have their own privacy policies.

Our privacy policy applies to all pages on our site

Should you need further guidance on how to proceed: External link for information about cookie management.

Send a message
X

Please use the forum for help with UI & libraries.

This message will be securely transmitted to our servers.