如何使用groovy在xml中追加一行

时间:2011-06-01 08:14:38

标签: java xml groovy

我有这个xml,我想添加一个新的row

<rows>
  <row>
    <name>Abhishek</name>
    <host>abhishek123@cjb.net</host>
  </row>
  <row>
    <name>Simon</name>
    <host>a@a.com</host>
  </row>
<rows>

我使用MarkupBuilder(编写器)来创建这个xml,但现在我如何添加一个新的row元素

被修改

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)

1 个答案:

答案 0 :(得分:4)

要在Groovy中执行此操作,一个解决方案是:

import groovy.xml.StreamingMarkupBuilder

def xml = """<rows>
  <row>
    <name>Abhishek</name>
    <host>abhishek123@cjb.net</host>
  </row>
  <row>
    <name>Simon</name>
    <host>a@a.com</host>
  </row>
</rows>"""

def root = new XmlSlurper().parseText( xml )
root.appendNode {
  row {
    name( 'tim' )
    host( 'a@woo.com' )
  }
}

def outputBuilder = new StreamingMarkupBuilder()
String result = outputBuilder.bind{ mkp.yield root }