鉴于你目前拥有的XML:
String doc = '''<entityProps>
| <candidate> <id>1</id><key></key> </candidate>
| <candidate> <id>2</id><key></key> </candidate>
| <candidate> <id>3</id><key></key> </candidate>
| <candidate> <id>4</id><key></key> </candidate>
|</entityProps>'''.stripMargin()
以及分段字符串:
String frag = '<candidate> <id>5</id><key></key> </candidate>'
可以解析文档:
def xml = new XmlSlurper().parseText(doc)
和碎片:
def fragxml = new XmlSlurper().parseText(frag)
然后,片段附加到文档的根节点:
xml.appendNode(fragxml)
而这个文档流回到一字符串:
String newDoc = new groovy.xml.StreamingMarkupBuilder().bind { mkp.yield xml }
println newDoc
即打印:
<entityProps>
<candidate><id>1</id><key></key></candidate>
<candidate><id>2</id><key></key></candidate>
<candidate><id>3</id><key></key></candidate>
<candidate><id>4</id><key></key></candidate>
<candidate><id>5</id><key></key></candidate>
</entityProps>
(我自己添加了换行符以方便阅读......您获得的实际字符串全部在一行上)