Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: fetch xmlunit using @grab instead of //require...

Here is an example of using Java's DOM facilities to create a new XML file:

Code Block

// require(groupId:'xmlunit', artifactId:'xmlunit', version:'1.0')
import javax.xml.parsers.DocumentBuilderFactory
import org.custommonkey.xmlunit.*

@Grab('xmlunit:xmlunit:1.3')

def addCar(document, root, name, make, year, country, type, text) {
    def car = document.createElement('car')
    car.setAttribute('name', name)
    car.setAttribute('make', make)
    car.setAttribute('year', year)
    root.appendChild(car)
    def countryNode = document.createElement('country')
    countryNode.appendChild(document.createTextNode(country))
    car.appendChild(countryNode)
    def record = document.createElement('record')
    record.setAttribute('type', type)
    record.appendChild(document.createTextNode(text))
    car.appendChild(record)
}

def builder  = DocumentBuilderFactory.newInstance().newDocumentBuilder()
def document = builder.newDocument()
def root     = document.createElement('records')

document.appendChild(root)
addCar(document, root, 'HSV Maloo', 'Holden', '2006', 'Australia',
        'speed', 'Production Pickup Truck with speed of 271kph')
addCar(document, root, 'P50', 'Peel', '1962', 'Isle of Man',
        'size', 'Smallest Street-Legal Car at 99cm wide and 59 kg in weight')
addCar(document, root, 'Royale', 'Bugatti', '1931', 'France',
        'price', 'Most Valuable Car at $15 million')

// now load in our XML sample and compare it to our newly created document
def builder2    = DocumentBuilderFactory.newInstance().newDocumentBuilder()
def inputStream = new ByteArrayInputStream(XmlExamples.CAR_RECORDS.bytes)
def control     = builder2.parse(inputStream)

XMLUnit.setIgnoreWhitespace(true)
def xmlDiff = new Diff(document, control)
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
XML Example
XML Example

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