Fork me on GitHub

Programming, Internet & more

Parse XML files with Groovy

Have you ever wondered how to parse a XML document with Groovy?

Assume that we have the following xml stored in the file notes.xml:


<notes>
    <note>
        <to>John</to>
        <from>Kyle</from>
        <heading>Reminder</heading>
        <body>Don't forget me this weekend!</body>
    </note>
    <note>
        <to>Alex</to>
        <from>Dave</from>
        <heading>Grocery list</heading>
        <body>Milk and Cheese</body>
    </note>
</notes>

Parsing this document with Groovy is really simple. To retrieve the note from Dave we can use the following code:


// parse
def xml = new XmlSlurper().parse("notes.xml")

// find nodes by from
def nodes = xml.depthFirst().find {
    it.name() == 'note' && it.getProperty('from') == 'Dave'
}

// print results
println(nodes)

That’s it. It’s just that simple.

Category: programming
-->

Post a Comment

Your email is kept private. Required fields are marked *

*
*