How can I select the root value of a node not including its children?

482 Views Asked by At

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
    }

};
1

There are 1 best solutions below

0
Kaus2b On

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