Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

Monday, December 29, 2008

XmlParser trim whitespace by default

I just found out that groovy.util.XmlParser trims whitespace by default. When parsing XML files with text nodes that contain trailing whitespace, for example, whitespace is removed in the Node returned by the parser.

def parser = new XmlParser()
def doc = parser.parseText("ABC ")
assert doc.data.text() == "ABC" // Not "ABC "!


To preserve whitespace, set the trimWhitespace property to false:

def parser = new XmlParser(trimWhitespace: false)
def doc = parser.parseText("ABC ")
assert doc.data.text() == "ABC "

Wednesday, March 19, 2008

Create recursive markup with MarkupBuilder

I just found a way use Groovy's MarkupBuilder to build an XML file with nested elements. Assuming I have a container with a collection of X objects and a Y object. The XML output of the container can be generated as follows:

import groovy.xml.*

class X {
private int id
private String name

def toXML = { builder ->
builder.x(id: id, name)
}
}

class Y {
private Date date = new Date()
def toXML = { builder ->
final sdf = new java.text.SimpleDateFormat("yyyyMMdd'T'HH:mm:ssZ")
builder.y(date: sdf.format(date))
}
}

def w = new StringWriter()
def xml = new MarkupBuilder(w)
xml.doubleQuotes = true
def xa = [ new X(id: 1, name: "x-name"), new X(id: 2, name: 'x-name2') ]
def yObj = new Y()
xml.root() {
agent(id: 1, name: 'agent1', "X")
xa.each { xo ->
xo.toXML(xml)
}
yObj.toXML(xml)
}
w.close()

The variable w is equivalent to:

<root>
<agent id="1" name="agent1">X</agent>
<x id="1">x-name</x>
<x id="2">x-name2</x>
<y date="20080318T23:56:54+0800" />
</root>

Notice that to get the builder to output double quotes for attributes, I set the doubleQuotes property to true.