0

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?

ChrisG29
  • 1,501
  • 3
  • 25
  • 45

2 Answers2

0

I fixed up your xml and providing an answer here:

def text = '<?xml version="1.0" encoding="UTF-8"?>' +
            '<cons:Consumer xmlns:cons="urn:corp:cons">' +
            '    <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>' +
            '</cons:Consumer>'

    def consumer = new XmlSlurper().parseText(text)

    println "Consumer first name: ${consumer.ConsumerName.FirstName}"

Output:

Consumer first name: Robert
  • Thanks, but it failed for me with the error: groovy.lang.MissingPropertyException: No such property: consumer for class: I managed to get it working, I'll add my solution. – ChrisG29 Jun 16 '19 at 21:23
0

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
ChrisG29
  • 1,501
  • 3
  • 25
  • 45