鉴于您当前拥有的 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>
(我自己添加了换行符以使其更易于阅读......你得到的实际字符串都在一行上)