2012-06-20 45 views
2

我试图通过SOAPUI向请求添加新节点Groovy 我有字符串XMl片段,但无法使用Groovy for SOAPUI创建节点。将字符串XML片段转换为Groovy中的文档节点

例如

<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> 

我想新<candidate></candidate>节点添加到该请求。 我已经有字符串,但我需要将其转换为Document节点。

回答

2

鉴于你目前拥有的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> 

(我自己添加了换行符以方便阅读......您获得的实际字符串全部在一行上)