How to convert xml files to groovy syntax from command line
is there any way to convert xml file to groovy syntax to be used in Xml MarkupBuilder? For example: the foo.xml file look like:
<foo attribute1="value1" attribute2="value2">
<nestedFoo>
sampleText
</nestedFoo>
</foo>
Then exec开发者_如何学Goute the the command line that I'm looking for:
<command line> foo.xml foo.groovy
the foo.groovy will look something like this:
foo(attribute1:'value1', attribute2:'value2') {
nestedFoo('sampleTest')
}
Thank you very much.
I came up with this:
Given some example XML:
def xml = """<foo attribute1="value1" attribute2="value2">
<nestedFoo>
sampleText
</nestedFoo>
</foo>"""
We can then parse it in using XmlParser
, and work through the nodes, writing data to a writer
def s = new XmlParser().parseText( xml )
// Closure for writing the xml to a writer as Groovy
// builder style code
def dumpNode
dumpNode = { node, writer, indent = ' ' ->
// Contents of the node, followed by the attributes
def attrs = node.text()?.trim()
attrs = attrs ? [ "'$attrs'" ] : []
attrs = node.attributes().inject( attrs ) { a, v ->
a << "$v.key:'$v.value'"
}.join( ', ' )
// write out the method definition
writer << "${indent}${node.name()}( $attrs )"
writer << ' {\n'
node.children().each {
if( it instanceof Node ) dumpNode( it, writer, " $indent" )
}
writer << "$indent}\n"
}
def sw = new StringWriter()
sw << 'println new StringWriter().with { out ->\n'
sw << ' new groovy.xml.MarkupBuilder( out ).with { smb ->\n'
dumpNode( s, sw )
sw << ' }\n'
sw << ' out.toString()\n'
sw << '}\n'
println sw
Running this code, prints out:
println new StringWriter().with { out ->
new groovy.xml.MarkupBuilder( out ).with { smb ->
foo( attribute1:'value1', attribute2:'value2' ) {
nestedFoo( 'sampleText' ) {
}
}
}
out.toString()
}
Then, if you run that in Groovy, you get:
<foo attribute1='value1' attribute2='value2'>
<nestedFoo>sampleText</nestedFoo>
</foo>
精彩评论