Search code examples
groovyxmlslurper

Groovy XML SLurper can't access child node


I've recently started using XML Slurper and am trying to access a specific child node from a SOAP envelope. Below is an extract of the XML I'm working with:

<cons:ConsumerName>
 <cons:FirstName>Robert</cons:FirstName>
 <cons:MiddleName>John</cons:MiddleName>
 <cons:FamilyName>Smith</cons:FamilyName>
</cons:ConsumerName>

<cons:ContactPersonName>
 <cons:FirstName>William</cons:FirstName>
 <cons:MiddleName>Michael</cons:MiddleName>
 <cons:FamilyName>Doe</cons:FamilyName>
</cons:ContactPersonName>

I'm trying to access the value of FirstName in the ConusmerName block, I've only been able to get a list of both of the first name values by using:

def block = new XmlSlurper().parseText(text).'**'.findAll{it.name()=='FirstName'}

I tried to get the first name for the ConsumerName block only, by using:

def block = new XmlSlurper().parseText(text).'ConsumerName'.findAll{it.name()=='FirstName'}

But nothing gets returned by that, I can't work out what I'm doing wrong?


Solution

  • To get the firstName value in the ConsumerName block of XML, I used the following:

    def text = new File(requestFilePath).text
    def fieldValue = new XmlSlurper().parseText(text).'**'.findAll{it.name()==tagBlockName}.getAt(tagName)[0]
    def var = (String)fieldValue