Parse xml using XmlSlurper in Groovy

3.7k views Asked by At

I have an xml response which looks like :-

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <multiRef xmlns:ns9="http://hero.ar.vixo.in" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" id="id2" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xsi:type="ns9:IdentityModel">
         <vixId xsi:type="xsd:int">13364719</vixId>
      </multiRef>
   </soapenv:Body>
</soapenv:Envelope>

This response is stored in a String name xmlMsg I am trying to parse it as follows:-

def xml = new XmlSlurper().parseText(xmlMsg);
def vixId = xml.Body.multiRef.vixId.text()

But the problem here is that before reading vixId i want to verify if 'type' in multiRef tag is IdentityModel

I tried accessing type as follows, but in vain :-

def vixId = [email protected]()

Please note that i am able to access id in multiRef tag using as follows:-

 def vixId = [email protected]()

Please help me in accessing type in multiRef tag

EDIT: Please note that i want to parse the type in multiRef tag without using name space like multiRef.'@xsi:type' because my namespace could change. All i want is that multiRef tag has a attribute type and that has a value of IdentityModel.. Only if this is there then I want to read vixId. Also note that with groovy 1.8 i was parsing it without namespace using multiRef.@type but it has stopped working ever since i updated groovy to 2.4.7

PS:- I am fairly new in dealing with xmls

2

There are 2 answers

2
CodeMonkey On

By default XMLSlurper is not namespace aware. This can be turned on by declaring namespaces with the declareNamespace Method.

def xml = new XmlSlurper().parseText(xmlMsg)
             .declareNamespace('xsi' : 'http://www.w3.org/2001/XMLSchema-instance')
def vixId = xml.Body.multiRef.vixId.text()
println vixId

def type = xml.Body.multiRef.@'xsi:type'.text()
println type

The output is:

13364719
ns9:IdentityModel

This returns the string value ns9:IdentityModel which is the exact value in the XML. If want to strip the namespace prefix, can do something like type = type.replace('ns9:','') to end up with "IdentityModel".

0
the_D On

Did not exactly find what i was looking for yet, but i have used a temporary workaround for the time being :-

    if (xml.Body.multiRef.attributes().toString().contains("IdentityModel")) {
        vixId = xml.Body.multiRef.vixId.text()
    }

Here attributes() method will give an array of all the attributes, their namespaces and values