如何从 xml 中检索属性

How to retrieve an attribute from an xml

我第一次使用 XMLParser 从 xml:

检索响应

代码如下:

import groovy.xml.XmlUtil
def response = testRunner.testCase.getTestStepByName("GetTestStep").getProperty("Response").getValue();
def root = new XmlParser().parseText( response )

log.info root

root 的 log.info 显示以下 xml 响应:

:{http://schemas.xmlsoap.org/soap/envelope/}Envelope[attributes={}; value=[{http://schemas.xmlsoap.org/soap/envelope/}Body[attributes={}; value=[{http://www.xxx}TestHotelResponse[attributes={}; value=[{http://www.xxx}AvailabilityRS[attributes={Url=http://xxx.xxxxxxxx.com }; value=[{http://www.xxx.es/xxxxxx/2007/}

现在我希望能够检索 AvailabilityRS 的属性,但是当我尝试通过此方法检索它时,我总是得到一个空白 []:

root.AvailabilityRS*.value()*.each { k, v ->
  log.info ("$k.localPart = $v")
}

RAW XML:

<soap:Envelope xmlns:soap="http://schemas.xxx">
   <soap:Body>
      <xxx xmlns="http://www.xxx7/">
         <xxx Url="http://xxx.xxxxxx.com">

如何检索 AvailabilityRS 属性中的 Url?

谢谢,

以下作品:

def str='''\
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <HotelAvailResponse xmlns="http://www.xxx/">
       <AvailabilityRS Url="http://xxx.xxxxxx.com" TimeStamp="2017-02-03T11:14:30.5744079+00:00" IntCode="xxx" />
    </HotelAvailResponse>
  </soap:Body>
</soap:Envelope>         
'''
def xml = new XmlParser().parseText(str)
def url = xml.'soap:Body'.HotelAvailResponse[0].AvailabilityRS[0].@Url
println url

请注意属性值的 @ 字符前缀。如果属性带有连字符或者不是有效的 groovy 标识符,您可以使用带引号的 node.'@attribute-name' 代替。

请注意,表达式 xml.'soap:Body'.HotelAvailResponse return 是一个节点列表,这就是我向两个表达式添加 [0] 的原因。观点是可能有任意数量的 HotelAvailResponse 节点,groovy 因此即使只有一个节点,return 也是一个列表。 运行 以上没有 [0] 索引将 return 一个以 url 作为元素的列表。

另请注意,通过 @ 字符访问属性的结果是一个字符串,而不是 xml 节点。

将您的脚本更改为以下内容,以检索 Url:
请注意,@ 需要用于检索属性。

def response = testRunner.testCase.getTestStepByName("GetHotelAvailability").getProperty("Response").getValue()
def parsedXml = new XmlSlurper().parseText(xml)
def url = parsedXml.'**'.find{ it.name() == 'AvailabilityRS' }.@Url.text()
log.info "Url is :${url}"

根据目前提供的两个答案进行一些实验。

这些都提供相同的结果:[http://stagejuniperws.xxxxxx.com]

// if you know the exact path
println root.'soap:Body'.HotelAvailResponse[0].AvailabilityRS*.@Url

// verbose code
println root.depthFirst().inject([]) {urls, node ->
    if (node.name().localPart == "AvailabilityRS") {
        urls << node.@Url
    }
    urls
}

// more concise
println root.depthFirst().findAll {it.name().localPart == "AvailabilityRS"}*.@Url

// more concise, use the GPath symbol '**'
println root.'**'.findAll {it.name().localPart == "AvailabilityRS"}*.@Url

// more concise, more GPath
println root.'**'.AvailabilityRS*.@Url