我想用 groovy 替换 xml 中的节点值。我在哈希图中的 xpath 中有值,如下所示:
def param = [:]
param["/Envelope/Body/GetWeather/CityName"] = "Berlin"
param["/Envelope/Body/GetWeather/CountryName"] = "Germany"
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
如何替换节点值?
您可以尝试使用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)
Run Code Online (Sandbox Code Playgroud)
另一种可能的解决方案
相反,如果您想使用完整路径而不仅仅是节点名称来更改其值(为了更稳健),您可以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"
Run Code Online (Sandbox Code Playgroud)
全部放在代码中:
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)
Run Code Online (Sandbox Code Playgroud)
请注意,在第二个解决方案中,我使用以下代码片段:
def node = xml
key.split("\\.").each {
node = node."${it}"
}
Run Code Online (Sandbox Code Playgroud)
这个片段来自这个答案和评论.,这是使用变量解决基于路径的解决方法(IMO 是一个很好的解决方法:))
希望这可以帮助,
| 归档时间: |
|
| 查看次数: |
10773 次 |
| 最近记录: |