0

If i have my GPath like this:

<Apple>
    <Mango>
        <id>5 </id>
    </Mango>
    <Mango>
        <id>10 </id>
    </Mango>
</Apple>

To get a Mango which has an id of 5, i would do,

GPathResult result = Apple.find{
it.Mango.id=5
}

But If my GPath was recursive. I mean, an apple can have a mango. And a Mango can again have an apple in it. For ex:

<Apple>
    <Mango>
        <id>10</id>
        <Apple>
            <Mango>
                <id>5 </id>
            </Mango>
         </Apple>
    </Mango>
</Apple>

How do I get the mango with an id of '5'. However recursive, the GPath might be(Mango with id '5' can be in any level of recursion), I need to find for mango with id of '5'. How can I achieve this with a find closure?

Advance Thanks

user1717230
  • 443
  • 1
  • 15
  • 30
  • Seems to be a dupe of http://stackoverflow.com/questions/6185746/groovy-map-find-recursive which has a reasonably good answer. – Bill K Apr 02 '13 at 21:55
  • hi Bill, I am a groovy newbie..and did not quite understand the answer in that thread. Could we do the same thing without using a map? – user1717230 Apr 02 '13 at 22:05
  • You should be able to, the constructs should be identical, but I haven't done the work to be sure. Give it a try--copy the code, get it working as is first then change the types to what you want and see if you can get it to work. Even if it doesn't help directly, it should teach you enough to solve the problem on your own. – Bill K Apr 02 '13 at 22:15

1 Answers1

2

You can use either breadthFirst or depthFirst, according to what best matches your structure:

def xml = '''<Apple>
    <Mango>
        <id>10</id>
        <Apple>
            <Mango found="correct">
                <id>5</id>
            </Mango>
         </Apple>
    </Mango>
</Apple>'''

nodes = new XmlParser().parseText xml

mango = nodes.breadthFirst().find { it.id.text() == "5" }

assert mango.@found == "correct"
Marmite Bomber
  • 19,886
  • 4
  • 26
  • 53
Will
  • 14,348
  • 1
  • 42
  • 44