使用Groovy的StreamingMarkupBuilder创建XML

此处是使用StreamingMarkupBuilder来创建一个新XML的示例:

// 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()

此处我们使用了XMLUnit来比较我们创建的XML和示例XML的区别,要想上述示例生效,需要确保示例XML是有效的,比如将下边的类加到你的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>
  '''
}

下边是另外一个演示如何产生混合内容(mixed content)的示例:

// 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()

另外你也可以参考使用MarkupBuilder来敏捷的创建XML

 
wiki/user_guide/creating_xml_using_groovy_s_streamingmarkupbuilder.txt · 最后更改: 2008-04-19 13:50 (外部编辑)
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki