1

//无法使用 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
4

1 回答 1

0

你打电话:

def fun = new ArrayList(root.listofthings.collect{it})

哪个设置fun为节点<listofthings>(顺便说一句,可以缩短为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

即:摆脱递归节点添加。

但是,我不确定你想用递归加法做什么,所以这可能不会做你想做的事情......你能解释更多你想看到的结果吗?

编辑

我设法让 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>
于 2012-04-02T08:55:17.493 回答