Creating tag with StreamingMarkupBuilder

2019-07-16 19:14发布

问题:

I am using StreamingMarkupBuilder to produce XML and I need to have a tag. Unfortunately I get exception :

Caught: java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.lang.Class

any ideas how I can create such tag?

import groovy.xml.StreamingMarkupBuilder
import org.custommonkey.xmlunit.*
import groovy.xml.XmlUtil

def xml = new StreamingMarkupBuilder().bind{
'use'(name:'Name', type:'type', year:2006) {
  desc('desc')
} 

} 

println xml.toString()

回答1:

You have to use the builder as a prefix to the keyword use, ie:

def xml = new StreamingMarkupBuilder().bind { smb ->
  smb.use( name:'Name', type:'type', year:2006 ) {
    desc( 'desc' )
  } 
} 

println xml.toString()

prints:

<use name='Name' type='type' year='2006'><desc>desc</desc></use>