0

I need to access the new value for each field if it exists, and the "previous" value in order to determine if a record has a change.

Sample XML Payload

<Persons>
    <Person>
        <id>8675309</id>
        <person>
            <action>CHANGE</action>
            <status>
                active
                <previous>inactive</previous>
            </status>
        </person>
    </Person>
    <Person>
        <id>8675308</id>
        <person>
            <action>CHANGE</action>
            <code>
                5678
                <previous>1234</previous>
            </code>
        </person>
    </Person>
</Persons>

I am using XmlParser/XmlSlurper to iterate over a similar xml payload that's provided from an API which includes the previous value in the field as a sub-field, how can I access just the root value of the status field in the above payload?

xml.each { it ->
    PersonId = it.id.text();
    Status = it.person.status.text(); // this is including the new and previous, 'activeinactive', and not just 'active'
    PrevStatus = it.person.status.previous.text();

    if (Status && PrevStatus) {
        // Status has changed, do something
    }

};
NDBoost
  • 10,184
  • 6
  • 53
  • 73
  • 1
    You can work by the children. E.g. `data.Person[0].person.status.children().first()` would give you only the first node (works here, but not sure, if that is always the case). This is a really bad way to structure data... – cfrick Sep 18 '21 at 14:09
  • Thank you for providing that snippet, I will try that out. I agree that it's a bad way to structure the data. However, that is the raw results from the vendors API that I'm trying to iterate over. If you provide it as an answer I will accept it. – NDBoost Sep 24 '21 at 15:18
  • @cfrick I think thats incorrect, By doing `children()` you get the child nodes. The text that is needed here is in the parent node itself. Posted answer below. – Kaus2b Oct 03 '21 at 03:38

1 Answers1

1

If you are using XmlParser, you need localText() instead of text()

Here is my test xml file

<Persons>
    <Person>
        <id>8675309</id>
        <person>
            <action>CHANGE</action>
            <status>
                active
                <previous>inactive</previous>
            </status>
        </person>
    </Person>
</Persons>

This is my script:

def xml = new XmlParser().parse("text.xml")

xml.each { it ->
    def personId = it.id.text();
    def status = it.person.status[0].localText()[0].trim()
    def prevStatus = it.person.status.previous.text();

    println status
    println prevStatus
};

Output after executing the script:

active
inactive

Note: I am using groovy3

Kaus2b
  • 747
  • 4
  • 12