xmlparsinggroovyxmlslurper

How to iterate through Nested XML after parsing using groovy with slurper or parser


I'm Facing an issue with iteration of below xml because it neglects some part. Can anyone guide me through this

<?xml version="1.0" encoding="UTF-8"?>
<fruits type="array">
    <fruit>
        <name>Apple</name>
        <alias>App</alias>
        <colors>
            <color>Red</color>
            <color>Green</color>
        </colors>
        <available-in type="array">
            <country>
                <name>Ind</id>
            </country>
            <country>
                <name>Ind</id>
            </country>
        </available-in>
    </fruit>
</fruits>

please find the Groovy code I used below

def map = new XmlSlurper().parseText(response).children().collectEntries{n->[(n.name()):{->n.children()?.collectEntries(owner)?:n.text()}()]};

Solution

  • You can use groovy's GPath capability called depthFirst() to iterate over all the children like so:

    def map = new XmlSlurper().parseText(response).depthFirst().collectEntries{[(it.name()): it.text()]}