【发布时间】:2016-06-22 01:00:36
【问题描述】:
设置:SOAP UI 5.2.0.,生成 XML 的 Groovy 步骤。
我们需要读取一个 CSV,其中包含类似 XPath 的节点位置和要放置以采样 XML 的新值。
以下答案中的最后一个版本的代码完全符合我们的目标:Groovy replace node values in xml with xpath
只有一个问题:
我们的 XML 包含重复元素并且无法使用,因为它会误解 Body.GetWeather[1].CityName 中的“[1]”
def node = xml
key.split("\\.").each {
node = node."${it}"
}
理想情况下,我们还需要使用Body.GetWeather[CountryName="Africa"].CityName 之类的东西。
我也尝试使用XMLParser 并尝试了语法(见下文)。我是 Groovy 的新手,我可能会遗漏一些东西。
所以,如果我需要以不同的方式解决问题,请告诉我。
下面是第三个例子中描述的实际问题:
// reading XML
def myInputXML = '''
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
<web:GetWeather xmlns:web="http://www.webserviceX.NET">
<web:CityName>Cairo</web:CityName>
<web:CountryName>Africa</web:CountryName>
</web:GetWeather>
<web:GetWeather xmlns:web="http://www.webserviceX.NET">
<web:CityName>Heidelberg</web:CityName>
<web:CountryName>Germany</web:CountryName>
</web:GetWeather>
<web:GetWeather xmlns:web="http://www.webserviceX.NET">
<web:CityName>Strasbourg</web:CityName>
<web:CountryName>France</web:CountryName>
</web:GetWeather>
</soapenv:Body>
</soapenv:Envelope>
'''
def xml = new XmlSlurper().parseText( myInputXML )
// Example 1 //
def GetAllCities = xml.Body.GetWeather.CityName
log.info ("Example 1: "+GetAllCities.text()) // references all 3 CityName nodes, prints out - CairoHeidelbergStrasbourg
// Example 2 //
def Get2ndCity = xml.Body.GetWeather[1].CityName
log.info ("Example 2: "+Get2ndCity.text()) // references 2nd node, prints out - Heidelberg
// Example 3 //
def tmpNode1 = "Body"
def tmpNode2 = "GetWeather[0]"
// This problem is with interpolation of GetWeather[0]. tmpNode2 = "GetWeather" would work as Example 1
def tmpNode3 = "CityName"
def GetFirstCity = xml."${tmpNode1}"."${tmpNode2}"."${tmpNode3}"
log.info ("Example 3: "+GetFirstCity.text()) // prints "" - WHY?
log.info ("Interpolation of tmpNodes 1, 2, 3:")
log.info ("${tmpNode1}") // prints Body
log.info ("${tmpNode2}") // prints GetWeather[0]
log.info ("${tmpNode3}") // prints CityName
附:抱歉,如果我的示例与实际问题无关,我认为它们有些帮助,但目标是改进提到的 stackoverflow 答案以支持重复元素。
【问题讨论】:
标签: xml xpath groovy soapui interpolation