Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added some headings and included some namespace examples

Simple Example

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

...

You may also want to see Using MarkupBuilder for Agile XML creation.As a final example

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:

...

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>