Simple Example
Here is an example of using Groovy's MarkupBuilder to create a new XML file:
| Code Block |
|---|
// require(groupId:'xmlunit', artifactId:'xmlunit', version:'1.0')
import groovy.xml.MarkupBuilder
import org.custommonkey.xmlunit.*
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:'P50', make:'Peel', year:1962) {
country('Isle of Man')
record(type:'size', 'Smallest Street-Legal Car at 99cm wide and 59 kg in weight')
}
car(name:'Royale', make:'Bugatti', year:1931) {
country('France')
record(type:'price', 'Most Valuable Car at $15 million')
}
}
XMLUnit.setIgnoreWhitespace(true)
def xmlDiff = new Diff(writer.toString(), XmlExamples.CAR_RECORDS)
assert xmlDiff.similar()
|
We have used XMLUnit to compare the XML we created with our sample XML. To do this, make sure the sample XML is available, i.e. that the following class is added to your CLASSPATH:
| Include Page | ||
|---|---|---|
|
You may also want to see Using MarkupBuilder for Agile XML creation.
DomToGroovy Example
Also, suppose we have an existing XML document and we want to automate generation of the markup without having to type it all in? We just need to use DomToGroovy as shown in the following example:
| Code Block |
|---|
import javax.xml.parsers.DocumentBuilderFactory import org.codehaus.groovy.tools.xml.DomToGroovy def builder = DocumentBuilderFactory.newInstance().newDocumentBuilder() def inputStream = new ByteArrayInputStream(XmlExamples.CAR_RECORDS.bytes) def document = builder.parse(inputStream) def output = new StringWriter() def converter = new DomToGroovy(new PrintWriter(output)) converter.print(document) println output.toString() |
Running this will produce the builder code for us.
Namespace Aware Example
Finally, here are some simple examples showing how to include namespaces and prefixes.
Prefix with Namespace
| Code Block |
|---|
def xml = new MarkupBuilder(writer)
xml.'rec:records'('xmlns:rec': 'http://groovy.codehaus.org') {
car(name:'HSV Maloo', make:'Holden', year:2006) {
country('Australia')
record(type:'speed', ' Truck with speed of 271kph')
}
}
result
<rec:records xmlns:rec='http://groovy.codehaus.org'>
<car name='HSV Maloo' make='Holden' year='2006'>
<country>Australia</country>
<record type='speed'> Truck with speed of 271kph</record>
</car>
</rec:records>
|
Default Namespace
| Code Block |
|---|
xml.records(xmlns: 'http://groovy.codehaus.org') {
car(name:'HSV Maloo', make:'Holden', year:2006) {
country('Australia')
record(type:'speed', ' Truck with speed of 271kph')
}
}
result
<records xmlns='http://groovy.codehaus.org'>
<car name='HSV Maloo' make='Holden' year='2006'>
<country>Australia</country>
<record type='speed'> Truck with speed of 271kph</record>
</car>
</records>
|