如何使用Node(Date)的值使用Groovy对XML进行排序

时间:2015-11-12 15:33:25

标签: xml sorting groovy

我无法使用Groovy对XML进行排序。我理解如何使用属性来做,但我想使用节点的值进行排序。

例如,我想通过StartDate对此XML进行排序:

<GetActivitiesByDatesResponse>
    <GetActivitiesByDatesResult>
        <Event>
            <EventCode>1244</EventCode>
            <Name>Event1</Name>
            <StartDate>2015-08-13T10:00:00</StartDate>
        </Event>
        <Event>
            <EventCode>1245</EventCode>
            <Name>Event2</Name>
            <StartDate>2015-07-15T10:00:00</StartDate>
        </Event>
        <Event>
            <EventCode>1246</EventCode>
            <Name>Event3</Name>
            <StartDate>2015-07-30T10:00:00</StartDate>
        </Event>
    </GetActivitiesByDatesResult>
</GetActivitiesByDatesResponse>

这是我的代码:

root = new XmlSlurper(false,false).parseText(payload)

if(root.name() == 'GetActivitiesResponse' || root.name() == 'GetActivitiesByDatesResponse')
{
    startEach = root.children().children()
}
else
{
    startEach = root.children()    
}
startEach.sort(true) {it.StartDate}


def xml = new StringWriter().with { w -> new groovy.xml.MarkupBuilder(w).with {
        mkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
                 escapeAttributes = false  
                 getPrinter().setAutoIndent(false);  
                 "newroot"() {
                    startEach.each { p -> "w_evenement"() {
                        ///allmylogic
                    }
                }
    }
    w.toString().replaceAll(">\\s+<", "><").trim();
}

我的有效载荷是我发布的更高的XML,因为它来自MuleESB,但只是假设它是一个字符串。

感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

您可以为给定的示例XML执行此操作:

def xml = '''<GetActivitiesByDatesResponse>
    <GetActivitiesByDatesResult>
        <Event>
            <EventCode>1244</EventCode>
            <Name>Event1</Name>
            <StartDate>2015-08-13T10:00:00</StartDate>
        </Event>
        <Event>
            <EventCode>1245</EventCode>
            <Name>Event2</Name>
            <StartDate>2015-07-15T10:00:00</StartDate>
        </Event>
        <Event>
            <EventCode>1246</EventCode>
            <Name>Event3</Name>
            <StartDate>2015-07-30T10:00:00</StartDate>
        </Event>
    </GetActivitiesByDatesResult>
</GetActivitiesByDatesResponse>'''

import groovy.xml.*

def x = new XmlParser().parseText(xml)

println XmlUtil.serialize(new StreamingMarkupBuilder().bind {
    GetActivitiesByDatesResponse {
        GetActivitiesByDatesResult {
            x.GetActivitiesByDatesResult[0]
             .children()
             .sort { Date.parse("yyyy-MM-dd'T'HH:mm:ss", it.StartDate.text()) }
             .each { e ->
                Event {
                    EventCode(e.EventCode.text())
                    Name(e.Name.text())
                    StartDate(e.StartDate.text())
                }
            }
        }
    }
})