Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Builders, DSLs and Templates

Parsing XML and JSON in Groovy

Read XML and JSON in Groovy with XmlSlurper, XmlParser and JsonSlurper: GPath navigation, attributes, findAll, large files, type checks and safe parsing.

Reading structured data is one of the places where Groovy feels much lighter than Java. XML and JSON documents become ordinary objects that you navigate with dots, so doc.library.book[0].title reads like the document itself. This navigation syntax is called GPath.

Groovy cannot run on this site, so the Groovy fences are read-only and the outputs shown are the ones you can derive exactly. The Java stand-ins parse the same data with the JDK so you can check the logic.

XmlSlurper

groovy.xml.XmlSlurper parses XML into a GPathResult.

GROOVY
import groovy.xml.XmlSlurper

def xml = '''
<library name="City">
  <book id="1" year="1965"><title>Dune</title><price>9.5</price></book>
  <book id="2" year="1815"><title>Emma</title><price>7.0</price></book>
  <book id="3" year="1965"><title>Children of Dune</title><price>11.0</price></book>
</library>
'''

def lib = new XmlSlurper().parseText(xml)

println lib.@name                       // City         (attribute)
println lib.book.size()                 // 3
println lib.book[0].title.text()        // Dune
println lib.book.@id*.text()            // [1, 2, 3]   (all id attributes)
println lib.book.findAll { it.@year == "1965" }.title*.text()   // [Dune, Children of Dune]
println lib.book.collect { it.price.toDouble() }.sum()   // 27.5

Rules of GPath:

  • .name selects children with that tag name (all of them, as a list-like result).
  • .@attr reads an attribute.
  • .text() returns the text of an element, and a node can be converted with .toInteger(), .toDouble(), .toString().
  • *. is the spread operator, so book.title*.text() collects every title.
  • [index] picks one element, .size() counts.
  • lib.'**' (or lib.depthFirst()) visits all descendants, so lib.'**'.findAll { it.name() == "title" } finds every title at any depth.

Namespaces

GROOVY
def doc = new XmlSlurper().parseText(xmlText).declareNamespace(
  atom: "http://www.w3.org/2005/Atom")
println doc.'atom:entry'.size()

When you parse with new XmlSlurper(false, true) (validating off, namespace aware on), tags are matched by local name and you can compare namespaceURI() yourself.

XmlParser versus XmlSlurper

XmlSlurper XmlParser
Result GPathResult, evaluated lazily groovy.util.Node tree, evaluated eagerly
Best for Reading, querying Reading and modifying the tree
Text of node node.text() node.text()
Add children Use replaceNode/appendNode then serialize node.appendNode(...) directly

With XmlParser, lib.book[0].title.text() still works, and node.attribute("id") is available. To write the modified tree back, use XmlNodePrinter or groovy.xml.XmlUtil.serialize(node).

JsonSlurper

groovy.json.JsonSlurper turns JSON text into maps, lists, strings, numbers and booleans.

GROOVY
import groovy.json.JsonSlurper

def data = new JsonSlurper().parseText('''
{
  "name": "Ada",
  "skills": ["math", "code"],
  "address": { "city": "London", "zip": null },
  "age": 36
}
''')

println data.name                  // Ada
println data.skills[1]             // code
println data.address.city          // London
println data.address.zip           // null
println data.age + 1               // 37
println data.skills.collect { it.toUpperCase() }   // [MATH, CODE]
println(data instanceof Map)       // true

Because the result is a plain Map/List, all the collection methods you know from collections apply: findAll, collect, groupBy, sum.

Other entry points: parse(File), parse(Reader), parse(URL), and parseText. The default parser type is a fast "index overlay"-style parser; you can choose a strategy with new JsonSlurper().setType(JsonParserType.LAX) to accept comments, single quotes and unquoted keys, or CHAR_BUFFER for streams.

Round trip

GROOVY
import groovy.json.JsonOutput

def text = JsonOutput.toJson(data)
println JsonOutput.prettyPrint(text)

Missing keys and safe navigation

GROOVY
println data.address?.country?.toUpperCase()    // null, no exception

Use ?. to skip null, and ?: to provide a default: data.nickname ?: "none".

Large inputs

JsonSlurper and XmlSlurper build the whole structure. For huge files:

  • Use XmlSlurper's lazy evaluation carefully and process one record at a time.
  • Use the JDK's StAX (XMLStreamReader) or Jackson's streaming API from Groovy, since Groovy calls Java libraries directly.
  • Never parse untrusted XML with external entities enabled. XmlSlurper has setFeature for disabling DTDs: parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) on your XmlSlurper instance before you call parseText.

Parsing untrusted XML can expose files or cause denial of service (XXE and entity-expansion attacks). Disable DOCTYPE declarations unless you truly need them. JSON has no such feature, but still validate the shape of the data before using it.

Try it: reading XML with the JDK (stand-in)

The Java stand-in does what XmlSlurper does: pick elements by name and read attributes and text.

Java Stand-in: navigating a small XML document

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: walking parsed data (stand-in)

A JSON document becomes maps and lists, and queries are collection operations. This program starts from already-parsed data and runs findAll/collect-style code with streams.

Java Stand-in: querying maps and lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you read the attribute id of the first book in lib.book[0]?

    GPath uses @ for attributes, so .@id reads the attribute and .id would look for a child element.
  2. 2. What type does JsonSlurper.parseText return for a JSON object?

    JSON objects become maps and JSON arrays become lists, so all collection methods apply.
  3. 3. When would you choose XmlParser over XmlSlurper?

    XmlParser builds a mutable Node tree, while XmlSlurper is a lazy, read-oriented view.
  4. 4. Which security setting is important when parsing untrusted XML?

    Disallowing DOCTYPE prevents XXE and entity-expansion attacks.

Summary

  • XmlSlurper reads XML through GPath: .child, .@attribute, .text(), *. and findAll.
  • XmlParser builds a mutable Node tree you can edit and serialize.
  • JsonSlurper returns plain maps and lists; JsonOutput writes them back.
  • Use ?. and ?: for missing data.
  • Disable DTDs for untrusted XML, and use streaming APIs for very large files.

Next: Template Engines