//无法使用xml slurper将替换的节点添加回xml。引发stackoverflow异常。现在想出怎么做
def xml = """<container>
<listofthings>
<thing id="100" name="foo"/>
</listofthings>
</container>"""
def root = new XmlSlurper().parseText(xml)
def fun = new ArrayList(root.listofthings.collect{it})
root.listofthings.thing.each {
it.replaceNode {}
}
root.listofthings.appendNode ( { thing(id:102, name:'baz') })
fun.each {
root.listofthings.appendNode it
}
def outputBuilder = new groovy.xml.StreamingMarkupBuilder()
String result = outputBuilder.bind { mkp.yield root }
print result
答案 0 :(得分:0)
你打电话:
def fun = new ArrayList(root.listofthings.collect{it})
哪个将fun
设置为节点<listofthings>
(并且btw可以缩短为:def fun = root.listofthings
)
然后就行:
fun.each {
root.listofthings.appendNode it
}
将此节点附加到节点<listofthings>
。这意味着您的树将永远不会结束(因为您将节点附加到自身),因此StackOverflowException
要使代码运行,您可以将其更改为:
import groovy.xml.StreamingMarkupBuilder
def xml = """<container>
| <listofthings>
| <thing id="100" name="foo"/>
| </listofthings>
|</container>""".stripMargin()
def root = new XmlSlurper().parseText(xml)
root.listofthings.thing*.replaceNode {}
root.listofthings.appendNode {
thing( id:102, name:'baz' )
}
def outputBuilder = new StreamingMarkupBuilder()
String result = outputBuilder.bind { mkp.yield root }
print result
ie:摆脱递归节点的添加。
但是,我不确定你在递归添加中尝试做什么,所以这可能不会做你想做的事情......你能解释一下你想看到的结果吗?
我设法让XmlParser做我认为你想做的事情吗?
def xml = """<container>
| <listofthings>
| <thing id="100" name="foo"/>
| </listofthings>
|</container>""".stripMargin()
def root = new XmlParser().parseText(xml)
def listofthings = root.find { it.name() == 'listofthings' }
def nodes = listofthings.findAll { it.name() == 'thing' }
listofthings.remove nodes
listofthings.appendNode( 'thing', [ id:102, name:'baz' ] )
nodes.each {
listofthings.appendNode( it.name(), it.attributes(), it.value() )
}
def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(root)
def result = writer.toString()
print result
打印:
<container>
<listofthings>
<thing id="102" name="baz"/>
<thing id="100" name="foo"/>
</listofthings>
</container>