我只想在SoapUI中使用groovy脚本来复制一个简单的节点并重命名它。但我不知道如何做到这一点。
输入xml是这样的:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<a>
<aa>...</aa>
</a>
<a>
<aa>...</aa>
</a>
<b>
<bb>...</bb>
</b>
<b>
<bb>..</bb>
</b>
</soap:Body>
我只需要为每个<b>
复制<bb>
到<bb2>
:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<a>
<aa>...</aa>
</a>
<a>
<aa>...</aa>
</a>
<b>
<bb>...</bb>
<bb2>...</bb2>
</b>
<b>
<bb>..</bb>
<bb2>...</bb2>
</b>
</soap:Body>
因为有多个&#34; b&#34;字段,我不能使用XPath转换的属性转移,所以我需要使用groovy脚本,但我没有找到任何有关该特定目的的帮助。
有人能给我一些提示吗?
我尝试使用daggett回答,但我的输入是SoapUI请求/响应。
def requestHolder = groovyUtils.getXmlHolder( "WSCall#Request" )
def xclone(Node n){
return new XmlParser().parseText(XmlUtil.serialize(n))
}
for( item in requestHolder.getDomNodes( "//b" )){
item.depthFirst().each{e->
if(e.name()=='bb'){
def e2 = xclone(e)
e2.name = 'bb2'
e.parent()?.append( e2 )
}
}
}
但我获得了groovy.lang.MissingMethodException: No signature of method: org.apache.xmlbeans.impl.store.Xobj$ElementXobj.depthFirst() is applicable for argument types: () values: [] error at line: 34
带
requestHolder.getDomNodes( "//b" ).each{e->
if(e.name()=='bb'){
def e2 = xclone(e)
e2.name = 'bb2'
e.parent()?.append( e2 )
}
}
我获得groovy.lang.GroovyRuntimeException: Cannot read write-only property: name
答案 0 :(得分:1)
import groovy.xml.XmlUtil
def root = new XmlParser().parseText('''<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<a>
<aa>...</aa>
</a>
<b>
<bb>111</bb>
</b>
<b>
<bb><cc>222</cc></bb>
</b>
</soap:Body>
</soap:Envelope>''')
def xclone(Node n){
return new XmlParser().parseText(XmlUtil.serialize(n))
}
root.depthFirst().each{e->
if(e.name()=='bb'){
def e2 = xclone(e)
e2.name = 'bb2'
e.parent()?.append( e2 )
}
}
println XmlUtil.serialize(root)
结果
<?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<a>
<aa>...</aa>
</a>
<b>
<bb>111</bb>
<bb2>111</bb2>
</b>
<b>
<bb>
<cc>222</cc>
</bb>
<bb2>
<cc>222</cc>
</bb2>
</b>
</soap:Body>
</soap:Envelope>