Builders and Working with XML/JSON

Site Admin · 11 Sep 2026 · 7 views

Groovy Builders

Builders in Groovy provide a clean DSL for creating structured data like XML, JSON, HTML, and Swing UIs. They use closures to define the structure hierarchically.

MarkupBuilder for XML

import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)

xml.books {
    book(title: "Groovy in Action", author: "Koenig")
    book(title: "Grails in Action", author: "Smith")
}

println writer.toString()

This produces well-formatted XML with proper nesting and indentation automatically.

JsonBuilder

import groovy.json.JsonBuilder

def builder = new JsonBuilder()
builder {
    name "Alice"
    age 30
    skills(["Groovy", "Grails", "Gradle"])
}

println builder.toPrettyString()

Parsing XML

Groovy makes XML parsing straightforward with XMLSlurper:

import groovy.xml.XmlSlurper

def xml = "<books><book title='Groovy'/></books>"
def books = new XmlSlurper().parseText(xml)

books.book.each { book ->
    println book.@title
}

Parsing JSON

import groovy.json.JsonSlurper

def json = '{"name": "Alice", "age": 30}'
def data = new JsonSlurper().parseText(json)

println data.name  // Alice
println data.age   // 30

Key Points

  • MarkupBuilder creates XML using a closure-based DSL.
  • JsonBuilder creates formatted JSON output.
  • XmlSlurper parses XML with dot-notation access.
  • JsonSlurper parses JSON into Groovy objects.
  • Builders produce properly structured output automatically.
Share this post:

Comments (0)

Please login or register to comment.