有没有办法将xml文件转换为在Xml MarkupBuilder中使用的groovy语法? 例如:foo.xml文件如下所示:
<foo attribute1="value1" attribute2="value2">
<nestedFoo>
sampleText
</nestedFoo>
</foo>
然后执行我正在寻找的命令行:
<command line> foo.xml foo.groovy
foo.groovy看起来像这样:
foo(attribute1:'value1', attribute2:'value2') {
nestedFoo('sampleTest')
}
非常感谢。
答案 0 :(得分:4)
我想出了这个:
给出一些XML示例:
def xml = """<foo attribute1="value1" attribute2="value2">
<nestedFoo>
sampleText
</nestedFoo>
</foo>"""
然后我们可以使用XmlParser
解析它,并通过节点,将数据写入编写器
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
运行此代码,打印出来:
println new StringWriter().with { out ->
new groovy.xml.MarkupBuilder( out ).with { smb ->
foo( attribute1:'value1', attribute2:'value2' ) {
nestedFoo( 'sampleText' ) {
}
}
}
out.toString()
}
然后,如果你在Groovy中运行它,你会得到:
<foo attribute1='value1' attribute2='value2'>
<nestedFoo>sampleText</nestedFoo>
</foo>