Sort XML child nodes by date field in Groovy Script

def body='''
<PerPerson>
  <employmentNav>
    <EmpEmployment>
      <jobInfoNav>
        <EmpJob>
          <event>10206</event>
          <userId>abc123</userId>
          <eventReason>RH</eventReason>
          <startDate>2020-10-05T00:00:00.000</startDate>
        </EmpJob>
        <EmpJob>
          <event>10186</event>
          <userId>abc123</userId>
          <eventReason>RL</eventReason>
          <startDate>2020-03-11T00:00:00.000</startDate>
        </EmpJob>
        <EmpJob>
          <event>10203</event>
          <userId>abc123</userId>
          <eventReason>HN</eventReason>
          <startDate>2019-12-16T00:00:00.000</startDate>
        </EmpJob>
        <EmpJob>
          <event>10190</event>
          <userId>abc123</userId>
          <eventReason>Z1</eventReason>
          <startDate>2020-06-13T00:00:00.000</startDate>
        </EmpJob>
        <EmpJob>
          <event>10193</event>
          <userId>abc123</userId>
          <eventReason>ZC</eventReason>
          <startDate>2020-03-11T00:00:00.000</startDate>
        </EmpJob>
        <EmpJob>
          <event>10189</event>
          <userId>abc123</userId>
          <eventReason>RW</eventReason>
          <startDate>2020-06-13T00:00:00.000</startDate>
        </EmpJob>
        <EmpJob>
          <event>10180</event>
          <userId>abc123</userId>
          <eventReason>FU</eventReason>
          <startDate>2020-04-15T00:00:00.000</startDate>
        </EmpJob>
      </jobInfoNav>
    </EmpEmployment>
  </employmentNav>
</PerPerson>
'''

def xml =  new XmlParser().parseText(body)
def jobInfoNav = xml.employmentNav.EmpEmployment.jobInfoNav[0]
//get value - array of child nodes, sort, and set it back
jobInfoNav.value = jobInfoNav.value().sort{ e-> e.startDate.text() }

groovy.xml.XmlUtil.serialize(xml)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top