lospejos lospejos - 8 months ago 125
Groovy Question

Find maximum value of attribute with Groovy XmlSlurper

Given xml:

<r1 dt="2011-06-10">
<r11 dt="2012-07-10" />
<r12 rdt="2011-10-11">
<r121 dt="2010-05-13" />
<r21 dt="2011-10-10"><n2 ddt="2012-11-31"/>dt</r21>
<r22 dt="2013-07-10"><n2 ddt="2013-06-31"/>dt</r22>
<r23 dt="2014-06-10"><n2 ddt="2014-03-31"/>dt</r23>
<r24 dt="2015-06-10"><n2 ddt="2011-10-31"/>dt</r24>

I need to find value among attributes
that has maximum date using Groovy XmlSlurper. In the given example it will be
. Suppose xml tree structure and deep is unknown (varies). Is it possible to do it using
, or should I do some iterations in my code?


Assuming s is string containing xml:

def x = new XmlSlurper().parseText(s)

Then this will get you a list of all dt attribute values

def list = x.depthFirst().findAll { it.@dt != "" }​.collect {it.@dt}​​​

you can use a similar bit of code to get lists of all rdt and ddt. Put em all into a single list and then just get max you can do:

l.max { a, b -> 
    new Date().parse("yyyy-MM-dd", a.toString()) <=> new Date().parse("yyyy-MM-dd", b.toString())
} ​