我有一些我用XmlSlurper解析的xml,我想添加一个新节点,然后引用该新节点。这表明了我正在尝试做的事情。除此之外的任何解决方案1.添加节点2.序列化3.再次解析4.引用新节点?
import groovy.xml.XmlUtil
def xml = new XmlSlurper().parseText("<foo/>")
xml.appendNode({bar()});
//now try to append something to bar. Probably doesn't work because it's a closure
xml.bar.appendNode({baz()})
//no baz inside bar
println XmlUtil.serialize(xml)
感谢。
编辑:
您必须使用XMLParser才能使其正常工作:
import groovy.xml.XmlUtil
//slurper - does NOT work
def xml = new XmlSlurper().parseText("<foo/>")
xml.appendNode({bar()});
//now try to append something to bar
xml.bar.appendNode({baz()})
//no baz inside bar
println XmlUtil.serialize(xml)
//parser - works
xml = new XmlParser().parseText("<foo/>")
xml.appendNode('bar');
//now try to append something to bar
xml.bar.first().appendNode('baz')
//no baz inside bar
println XmlUtil.serialize(xml)
为什么在这篇文章的答案中有解释:
答案 0 :(得分:1)
使用方法有什么问题?
import groovy.xml.XmlUtil
def xml = new XmlSlurper().parseText( "<foo/>" )
xml.appendNode {
bar {
baz()
}
}
println XmlUtil.serialize( xml )