我想在groovy中替换xml中的节点值。 我在散列映射中的xpath中有值:
def param = [:]
param["/Envelope/Body/GetWeather/CityName"] = "Berlin"
param["/Envelope/Body/GetWeather/CountryName"] = "Germany"
XML文件:
<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<web:GetWeather xmlns:web="http://www.webserviceX.NET">
<web:CityName>Test</web:CityName>
<web:CountryName>Test</web:CountryName>
</web:GetWeather>
</soapenv:Body>
</soapenv:Envelope>
如何替换节点值?
答案 0 :(得分:1)
您可以尝试使用XmlSlurper
,但这可能是一种简单的方法。您可以使用节点名称作为键来定义映射,将文本作为值进行迭代,从而更改Xml中的节点。您可以使用类似下面代码的内容:
import groovy.util.XmlSlurper
import groovy.xml.XmlUtil
def xmlString = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<web:GetWeather xmlns:web="http://www.webserviceX.NET">
<web:CityName>Test</web:CityName>
<web:CountryName>Test</web:CountryName>
</web:GetWeather>
</soapenv:Body>
</soapenv:Envelope>'''
def param = [:]
param["CityName"] = "Berlin"
param["CountryName"] = "Germany"
// parse the xml
def xml = new XmlSlurper().parseText(xmlString)
// for each key,value in the map
param.each { key,value ->
// change the node value if the its name matches
xml.'**'.findAll { if(it.name() == key) it.replaceBody value }
}
println XmlUtil.serialize(xml)
另一种可能的解决方案
相反,如果您想使用完整路径而不仅仅是节点名称来更改其值(更加健壮),您可以使用XPath
表示法而不是.
来定义/
。符号并避免根节点名称(在您的情况下为Envelope
),因为在解析的xml对象中它已经存在。所以改变你的XPath你可以有类似的东西:
def param = [:]
// since envelope is the root node it's not necessary
param["Body.GetWeather.CityName"] = "Berlin"
param["Body.GetWeather.CountryName"] = "Germany"
代码中的所有内容:
import groovy.util.XmlSlurper
import groovy.xml.XmlUtil
def xmlString = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<web:GetWeather xmlns:web="http://www.webserviceX.NET">
<web:CityName>Test</web:CityName>
<web:CountryName>Test</web:CountryName>
</web:GetWeather>
</soapenv:Body>
</soapenv:Envelope>'''
def param = [:]
// since envelope is the root node it's not necessary
param["Body.GetWeather.CityName"] = "Berlin"
param["Body.GetWeather.CountryName"] = "Germany"
def xml = new XmlSlurper().parseText(xmlString)
param.each { key,value ->
def node = xml
key.split("\\.").each {
node = node."${it}"
}
node.replaceBody value
}
println XmlUtil.serialize(xml)
请注意,在第二个解决方案中,我使用此代码段:
def node = xml
key.split("\\.").each {
node = node."${it}"
}
来自此answer和comment的此代码段,它是使用变量解决.
路径的解决方法(一个很好的解决方法IMO :)
)< / p>
希望这有帮助,