Skip to content
Philip Ford edited this page Jan 1, 2017 · 2 revisions

Introduction

For reading XML, use either groovy.util.XmlParser or groovy.util.XmlSlurper. Both have the same approach to parsing xml. Both come with overloaded parse() methods plus some special methods such as parseText(), parseFile() and others.

Traversing XML

The most common way of querying XML in Groovy is using GPath

GPath is a path expression language, similar to XPath, integrated into Groovy which allows parts of nested structured data to be identified. Again, it is similar to XPath expressions, but you can use it with POJO classes as well as XML. As an example, you can specify a path to an object or element of interest:

a.b.c → for XML, yields all the elements inside inside

a.b.c → all POJOs, yields the properties for all the properties of (sort of like a.getB().getC() in JavaBeans)

For XML, you can also specify attributes, e.g.:

  • a["@href"] → the href attribute of all the a elements
  • a.'@href' → an alternative way of expressing this
  • a.@href → an alternative way of expressing this when using XmlSlurper

Reading XML

Reading XML From Strings

Use parseText() of either XmlParser or XmlSlurper. parseText() take an XML String as input and recursively converts it to a list or map of objects.

def String books = '''
    <response version-api="2.0">
        <value>
            <books>
                <book available="20" id="1">
                    <title>Don Xijote</title>
                    <author id="1">Manuel De Cervantes</author>
                </book>
                <book available="14" id="2">
                    <title>Catcher in the Rye</title>
                   <author id="2">JD Salinger</author>
               </book>
               <book available="13" id="3">
                   <title>Alice in Wonderland</title>
                   <author id="3">Lewis Carroll</author>
               </book>
               <book available="5" id="4">
                   <title>Don Xijote</title>
                   <author id="4">Manuel De Cervantes</author>
               </book>
           </books>
       </value>
    </response>
'''

def response = new XmlSlurper().parseText(books)
def authorResult = response.value.books.book[0].author

assert authorResult.text() == 'Manuel De Cervantes'

Reading XML From Files

Use the parse() method of either XmlParser or XmlSlurper. The parse method takes a String for the file path as input.

def file = '/Users/paford/local/wlp/usr/servers/laissa/server.xml'
def parser = new XmlParser()
def response = parser.parse(file)
println(response.webApplication.last()["@context-root"])

Writing XML

The most commonly used approach for creating XML with Groovy is to use a builder, i.e. one of:

  • groovy.xml.MarkupBuilder
  • groovy.xml.StreamingMarkupBuilder

Writing XML to Strings

import groovy.xml.MarkupBuilder

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

xml.records() { 
    car(name:'HSV Maloo', make:'Holden', year:2006) {
        country('Australia')
        record(type:'speed', 'Production Pickup Truck with speed of 271kph')
    }
    car(name:'Royale', make:'Bugatti', year:1931) {
        country('France')
        record(type:'price', 'Most Valuable Car at $15 million')
    }
}

def records = new XmlSlurper().parseText(writer.toString()) 

println records.car.first()["@name"]

Writing XML to Files

Adding/Altering/Removing Nodes

Adding Nodes

  • Open the file with XmlParser.parse(filePath).
  • Call appendNode() on the response.
    • appendNode() takes a the following parameters:
      • A QName() object (a node)
      • A map for the attributes. If no attributes use [:].
      • The value (optional)
  • Print the output to a file using XmlNodeWriter, which takes a PrintWriter as input, which in turn takes a FileWriter as input.
    • In the example below, we print the altered XML to another file.
def file = '/Users/paford/local/wlp/usr/servers/laissa/server.xml'
def out = "/Users/paford/Desktop/server.xml"
def parser = new XmlParser()
def response = parser.parse(file)
response.appendNode(
    new QName("webApplication"),
    [id: "medius-ui",
    location: "/users9/emra-sandbox/local/wwww/medius-ui.war",
    "context-root": "/ui/emra"]
 )

XmlNodePrinter printer = new XmlNodePrinter(new PrintWriter(new FileWriter(out)))
printer.preserveWhitespace = true
printer.print(response)

References

Clone this wiki locally