Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: note about return value of SMB.bind
Wiki Markup
Here is an example of using {{StreamingMarkupBuilder}} to create a new XML file:

...


{code
}
// require(groupId:'xmlunit', artifactId:'xmlunit', version:'1.1beta2')
import groovy.xml.StreamingMarkupBuilder
import org.custommonkey.xmlunit.*

def xml = new StreamingMarkupBuilder().bind{
  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.ignoreWhitespace = true
def xmlDiff = new Diff(xml.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:

...

Here's another example illustrating how to produce mixed content:

Code Block
{code}
Note that {{StreamingMarkupBuilder.bind}} returns a
{http://groovy.codehaus.org/gapi/groovy/lang/Writable.html Writable}
instance that may be used to stream the markup to a {{Writer}}, in addition to capturing the output in a String (as shown above).
We have used [XMLUnit|http://xmlunit.sourceforge.net/] 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:XML Example}
Here's another example illustrating how to produce mixed content:
{code}
// require(groupId:'xmlunit', artifactId:'xmlunit', version:'1.1beta2')
import groovy.xml.StreamingMarkupBuilder
import org.custommonkey.xmlunit.*

def message = ' <b>wins</b> '
def xml = new StreamingMarkupBuilder().bind{
  html() {
    body(bgcolor:'red') {
      h1('In Breaking News ...')
      p {
        a(href:'http://groovy.codehaus.org', 'Groovy')
        mkp.yieldUnescaped message
        a(href:'http://jax-award.de/jax_award/gewinner_eng.php', 'Jax')
        mkp.yield ' praise & award.'
} } } }

def expected = '''
<html>
    <body bgcolor='red'>
        <h1>In Breaking News ...</h1>
        <p>
            <a href='http://groovy.codehaus.org'>Groovy</a>
            <b>wins</b>
            <a href='http://jax-award.de/jax_award/gewinner_eng.php'>Jax</a>
            praise &amp; award.
        </p>
    </body>
</html>
'''

XMLUnit.ignoreWhitespace = true
def xmlDiff = new Diff(xml.toString(), expected)
assert xmlDiff.similar()
{code}
You may also want to see [Using MarkupBuilder for Agile XML creation].