XML Processing and GPath
34.1 XmlSlurper (Lazy, GPath)
import groovy.xml.XmlSlurper
def xml = '''
<library>
<book id="1" year="2015"><title>Groovy in Action</title><author>König</author><price>45.5</price></book>
<book id="2" year="2008"><title>Programming Groovy</title><author>Subramaniam</author><price>30</price></book>
</library>'''
def lib = new XmlSlurper().parseText(xml)
println lib.book.size()
println lib.book[0].title.text()
println lib.book*.title*.text()
println lib.book.find { [email protected]() > 2010 }.title
println lib.book.findAll { it.price.toDouble() > 35 }*.author*.text()
println lib.'**'.findAll { it.name() == 'author' }*.text() // depth-first search
println lib.book.collect { "${it.@id}: ${it.title}" }
println lib.book.price*.toDouble().sum()34.2 XmlParser (Mutable Node Trees)
import groovy.xml.*
def root = new XmlParser().parseText(xml)
root.book[0].price[0].value = "40"
root.appendNode('book', [id: '3'], 'New Book')
root.book.findAll { it.@year == '2008' }.each { it.parent().remove(it) }
println XmlUtil.serialize(root)34.3 Namespaces, Streaming and Other Tools
XmlSlurper with declareNamespace(...), StreamingMarkupBuilder for output, XmlUtil.serialize, DOMBuilder/DOMCategory for DOM, groovy.xml.XmlNodePrinter, and XPath via javax.xml.xpath.
GPath is Groovy's path expression language. It works on XML, maps, and object graphs: people.address.city, list*.prop, '**' deep search.
Groovy 4 package names: groovy.xml.* (the old groovy.util.XmlSlurper was removed). Similar moves happened for groovy.json, groovy.ant, etc.