[groovy-user] Sort XML NodeList and replace old List

1,040 views
Skip to first unread message

RelleschB

unread,
Jul 18, 2013, 5:30:36 AM7/18/13
to us...@groovy.codehaus.org
Hello,

I want to sort some Elements in a list of XML Elements.
The sorting works.

The statement "*records.value = sorted*" works fine.
But I want "*records.records.value = sorted*" I get the following exception:
Caught: java.lang.IllegalArgumentException: argument type mismatch
java.lang.IllegalArgumentException: argument type mismatch
at
com.bsp.workflow.NormalizeWorkflow.nomalize(NormalizeWorkflow.groovy:44)
at com.bsp.workflow.NormalizeWorkflow$nomalize.call(Unknown Source)
at
com.bsp.workflow.NormalizeWorkflow.main(NormalizeWorkflow.groovy:5)

Here is the code:
def records = new XmlParser().parseText(XmlExamples.CAR_RECORDS)
def sorted = records.records.car.sort{ it.'@year'.toInteger() }
//records.value = sorted
records.records.value = sorted
println(records.toString())

static def CAR_RECORDS = '''
<records>
<records>
<car name='HSV Maloo' make='Holden' year='2006'>
<country>Australia</country>
<record type='speed'>Production Pickup Truck</record>
</car>
<car name='P50' make='Peel' year='1962'>
<country>Isle of Man</country>
<record type='size'>Smallest Street-Legal Car</record>
</car>
<car name='Royale' make='Bugatti' year='1931'>
<country>France</country>
<record type='price'>Most Valuable Car</record>
</car>
</records>
</records>
'''

Greets Björn



--
View this message in context: http://groovy.329449.n5.nabble.com/Sort-XML-NodeList-and-replace-old-List-tp5716243.html
Sent from the groovy - user mailing list archive at Nabble.com.

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

http://xircles.codehaus.org/manage_email


Tim Yates

unread,
Jul 18, 2013, 6:00:22 AM7/18/13
to us...@groovy.codehaus.org
You could try:

def xml = new XmlParser().parseText( CAR_RECORDS )
cars = xml.records.car.sort { it.@year.toInteger() }
xml.records.head().children().clear()
cars.each { xml.records.head().append( it ) }
println XmlUtil.serialize( xml ) 

Tim

Tim Yates

unread,
Jul 18, 2013, 6:26:10 AM7/18/13
to us...@groovy.codehaus.org
Or, you could use XmlSlurper and create a new document with StreamingMarkupBuilder:

def xml = new XmlSlurper().parseText( CAR_RECORDS )

new StreamingMarkupBuilder().bind {
  records {
    records {
      xml.records.car.collect().sort { it.@year.toInteger() }.each {
        mkp.yield it
      }
    }
  }
}

Tim

RelleschB

unread,
Jul 18, 2013, 7:53:49 AM7/18/13
to us...@groovy.codehaus.org
Hello,

thanks. Your first suggestion is what I need.

Greets Björn



--
View this message in context: http://groovy.329449.n5.nabble.com/Sort-XML-NodeList-and-replace-old-List-tp5716243p5716249.html
Reply all
Reply to author
Forward
0 new messages