Skip to: Site menu | Main content

Groovy 

      Download | Documentation | Developers | Community

An agile dynamic language for the Java Platform

Creating XML with Groovy and XOM Add comment to Wiki View in Wiki Edit Wiki page Printable Version

Here is an example of using XOM to create a new XML file:

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

def addCar(root, name, make, year, country, type, text) {
    def car = new Element('car')
    car.addAttribute(new Attribute('name', name))
    car.addAttribute(new Attribute('make', make))
    car.addAttribute(new Attribute('year', year))
    root.appendChild(car)
    def countryNode = new Element('country')
    countryNode.appendChild(country)
    car.appendChild(countryNode)
    def record = new Element('record')
    record.appendChild(text)
    record.addAttribute(new Attribute('type', type))
    car.appendChild(record)
}

def root     = new Element('records')
def document = new Document(root)

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

// convert resulting document to a string and compare with expected
XMLUnit.setIgnoreWhitespace(true)
def xmlDiff = new Diff(document.toXML(), 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:

XmlExamples.groovy
class XmlExamples {
  static def CAR_RECORDS = '''
    <records>
      <car name='HSV Maloo' make='Holden' year='2006'>
        <country>Australia</country>
        <record type='speed'>Production Pickup Truck with speed of 271kph</record>
      </car>
      <car name='P50' make='Peel' year='1962'>
        <country>Isle of Man</country>
        <record type='size'>Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record>
      </car>
      <car name='Royale' make='Bugatti' year='1931'>
        <country>France</country>
        <record type='price'>Most Valuable Car at $15 million</record>
      </car>
    </records>
  '''
}

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