Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Here is an example of using Groovy's MarkupBuilder to create a new XML file:

Code Block
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:'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')
  }
}

println writer.toString()

This will output XML similar to what we have been using in previous examples.

You may also want to see Using MarkupBuilder for Agile XML creation.

If we want we can take this further and compare what we produced with our sample XML. To do this, make sure the following class is added to your CLASSPATH:

...

We can now extend the previous example to compare the newly created XML with our sample XML using XMLUnit:

Code Block

// requires xmlunit.jar
// require(groupId:'xmlunit', artifactId:'xmlunit', version:'1.0')
import groovy.xml.MarkupBuilder
import org.custommonkey.xmlunit.Diff*

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)
xmlDiff.overrideDifferenceListener(new IgnoreWhitespaceDifferenceListener())
assert xmlDiff.similar()

We have a little bit of work to do. By default XMLUnit allows elements and attributes to be reordered and still treats two XML documents as similar but by default it doesn't allow differences in whitespace; hence the need for IgnoreWhitespaceDifferenceListener as shown belowused 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
GROOVY:XMLUnit DifferenceListenerXML Example
GROOVY:XMLUnit DifferenceListenerXML Example

As a final example, 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:

...