XML with XmlSlurper and MarkupBuilder

groovy-xml brings two tools: XmlSlurper reads a document into a tree that GPath walks, and MarkupBuilder writes one from nested closures.

Read with GPath

read.groovy

import groovy.xml.XmlSlurper def document = '''<catalog> <book id="1"><title>Groovy</title><price>9.99</price></book> <book id="2"><title>Gradle</title><price>24.99</price></book> </catalog>''' def catalog = new XmlSlurper().parseText(document) println catalog.book.size() println catalog.book[0].title.text() println catalog.book*.@id println catalog.book.findAll { it.price.toDouble() < 20 }*.title*.text()

groovy read.groovy

2
Groovy
[1, 2]
[Groovy]

A child element is a property, text() is its text and @id is an attribute. book is a GPathResult that behaves like a list of the matching nodes, so the spread operator and findAll work on it.

Build a document

build.groovy

import groovy.xml.MarkupBuilder def writer = new StringWriter() def xml = new MarkupBuilder(writer) xml.library { book(id: 1) { title('Groovy') author('Ada') } } println writer.toString()

groovy build.groovy

<library>
  <book id='1'>
    <title>Groovy</title>
    <author>Ada</author>
  </book>
</library>

The builder is the writing side of the builders lesson: one method per element, a named argument per attribute. Both classes are in the same jar, so a script that reads and writes XML needs nothing installed.

Namespaces and a note

A document with a namespace needs declareNamespace before GPath can find its elements, because the prefix in the document is not the prefix in the query. A large document is read with parse(File) like JSON, and a very large one wants a streaming parser, which is the one case this lesson does not cover.

Related

Article author: Arthur Isaev