Groovy's Native Data-Format Support
Groovy ships with first-class support for both XML and JSON without needing external libraries for basic use cases: XmlSlurper and XmlParser handle reading XML into a lazily-evaluated node tree navigable with GPath expressions, groovy.xml.MarkupBuilder generates XML or HTML using Groovy's builder pattern, and groovy.json.JsonSlurper/JsonOutput handle parsing and serializing JSON, all leveraging Groovy's dynamic typing and closures to keep the code terse compared to equivalent Java DOM or SAX parsing.
Cricket analogy: Much like a modern cricket stadium comes pre-fitted with Hawk-Eye and Snicko without needing to install separate third-party systems, Groovy ships with built-in XmlSlurper and JsonSlurper so you don't need external libraries for basic parsing.
Parsing and Building XML
XmlSlurper parses an XML document lazily and returns GPathResult objects that you navigate using GPath syntax like books.book[0].@title or books.book.findAll { it.@price.toDouble() > 20 }, where the dot-and-bracket chain mirrors XPath-style navigation but reads as ordinary Groovy property and closure syntax rather than a separate query language; XmlParser, by contrast, eagerly builds a Node tree and is preferred when you need to mutate the document, since XmlSlurper's lazy GPathResult nodes are harder to modify in place.
Cricket analogy: Much like a TV broadcast's ball-tracking overlay reads live match data without altering the actual game, XmlSlurper lazily reads an XML document via GPath without building a fully mutable tree, while XmlParser is used when you need to actually edit the document.
groovy.xml.MarkupBuilder builds XML by treating undefined method calls as element names via Groovy's methodMissing/dynamic dispatch, so builder.books { book(title: 'Groovy in Action', price: 39.99) } emits <books><book title='Groovy in Action' price='39.99' /></books> — nesting closures mirrors nesting elements, and named-argument maps become attributes, which makes generating structured XML far less verbose than manually building strings or using javax.xml.transform.
Cricket analogy: Much like a scorer fills in a physical scorebook where each nested column (overs, runs, wickets) corresponds to a structured entry, MarkupBuilder's nested closures like book(title: '...', price: 39.99) map directly to nested XML elements and attributes.
import groovy.xml.MarkupBuilder
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
// Building XML
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.books {
book(title: 'Groovy in Action', price: 39.99)
book(title: 'Making Java Groovy', price: 34.99)
}
println writer.toString()
// Parsing XML with XmlSlurper + GPath
def parsed = new XmlSlurper().parseText(writer.toString())
def expensive = parsed.book.findAll { it.@price.toDouble() > 35 }
expensive.each { println it.@title }
// JSON round-trip
def json = JsonOutput.toJson([name: 'Groovy', stable: true, version: 4])
println JsonOutput.prettyPrint(json)
def data = new JsonSlurper().parseText(json)
println "Version: ${data.version}"Working with JSON
groovy.json.JsonSlurper parses a JSON string or stream into native Groovy Map/List structures you can navigate immediately with normal property and index syntax like data.users[0].email, no separate binding classes required; JsonOutput.toJson(myMap) serializes any Groovy Map, List, or POGO back into a JSON string, and JsonOutput.prettyPrint(json) reformats it for readability, making Groovy a common choice for quick REST API scripting and configuration file processing.
Cricket analogy: Much like a live-scores app instantly turns a match feed into readable stats without a separate translator, JsonSlurper turns a JSON API response directly into navigable Groovy Maps and Lists like data.users[0].email with no binding classes.
GPath expressions like books.book.findAll { it.@price.toDouble() > 20 } are plain Groovy — @price accesses an XML attribute and .toDouble() is a normal Groovy method — so you don't need to learn a separate XPath dialect to query XML.
- XmlSlurper lazily parses XML into GPathResult objects, navigable with dot/bracket GPath syntax for querying.
- XmlParser eagerly builds a mutable Node tree, preferred when the XML document needs to be modified.
- MarkupBuilder generates XML/HTML by treating undefined method calls as element names via dynamic dispatch.
- Named-argument maps passed to MarkupBuilder closures become XML attributes automatically.
- JsonSlurper parses JSON directly into native Groovy Maps and Lists, with no binding classes required.
- JsonOutput.toJson serializes Groovy Maps/Lists/POGOs to JSON; prettyPrint reformats for readability.
- GPath queries use ordinary Groovy syntax (
@attr, closures, findAll) rather than a separate query language like XPath.
Practice what you learned
1. Which Groovy class parses XML lazily and returns GPathResult objects for querying?
2. Why would you choose XmlParser over XmlSlurper?
3. How does MarkupBuilder decide what XML element to emit for `book(title: 'X')`?
4. What does JsonSlurper.parseText(json) return for a JSON object?
5. What does JsonOutput.prettyPrint do?
Was this page helpful?
You May Also Like
Groovy Scripting for Automation
Learn how to use Groovy as a scripting language for file processing, running system commands, parsing command-line arguments, and building automation tools.
Groovy and Testing with Spock
Learn how the Spock Framework uses Groovy's syntax to write expressive, structured tests with given-when-then blocks, data tables, and built-in mocking.
Groovy and Gradle
Learn how Gradle uses Groovy as its build-script DSL, covering tasks, dependencies, plugins, and multi-project builds.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics