Search code examples
xmlgroovyxmlslurpergpath

Find maximum value of attribute with Groovy XmlSlurper


Given xml:

<d>
    <r1 dt="2011-06-10">
        <r11 dt="2012-07-10" />
        <r12 rdt="2011-10-11">
            <r121 dt="2010-05-13" />
        </r12>
    </r1>
    <r2>
        <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>
    </r2>
</d>

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


Solution

  • 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:

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