BruceyBandit BruceyBandit - 4 years ago 149
Groovy Question

How to retrieve an attribute from an xml

I am using XMLParser for the first time to retrieve a response from an xml:

Below is the code:

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

The of root displays the following xml response:

:{}Envelope[attributes={}; value=[{}Body[attributes={}; value=[{}HotelAvailResponse[attributes={}; value=[{}AvailabilityRS[attributes={Url=, TimeStamp=2017-02-03T11:14:30.5744079+00:00, IntCode=rUR62v5v88jHGszgh2jg1Ne6WmZwUAhxHaxdMby2qj4=}; value=[{}

Now I want to be able to retrieve the attribute for
which is [attributes={Url=].

However I keep getting a blank [] when I try to retrieve it via this method:

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


<soap:Envelope xmlns:soap="" xmlns:xsi="" xmlns:xsd="">
<HotelAvailResponse xmlns="">
<AvailabilityRS Url="" TimeStamp="2017-02-03T11:14:30.5744079+00:00" IntCode="rUR62v5v88jHGszgh2jg1Ne6WmZwUAhxHaxdMby2qj4=">

How can I retrieve the Url within the attribute for AvailabilityRS?


Answer Source

The following works:

def str='''\
<soap:Envelope xmlns:soap="" xmlns:xsi="" xmlns:xsd="">
    <HotelAvailResponse xmlns="">
       <AvailabilityRS Url="" TimeStamp="2017-02-03T11:14:30.5744079+00:00" IntCode="rUR62v5v88jHGszgh2jg1Ne6WmZwUAhxHaxdMby2qj4=" />
def xml = new XmlParser().parseText(str)
def url = xml.'soap:Body'.HotelAvailResponse[0].AvailabilityRS[0].@Url
println url

note the at @ character prefix for attribute values. If the attribute is hyphenated or otherwise not a valid groovy identifier, you can use a quoted node.'@attribute-name' instead.

Note that the expression xml.'soap:Body'.HotelAvailResponse returns a list of nodes which is why I added a [0] to both expressions. The sentiment is that there could be any number of HotelAvailResponse nodes and groovy therefore returns a list even if there is just one node. Running the above without the [0] indexing will return a list with the url as an element.

Note also that the result of an attribute access via the @ character is a string and not an xml node.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download