Search code examples
xmlsortinggroovy

how to sort the texts of xml nodes in groovy


I have this sample XML below:

<VqlQueryRestResult>
<data>
    <row>
        <Field3>BBB</Field3>
    </row>
    <row>
        <Field3>CCC</Field3>
    </row>
    <row>
        <Field3>AAA</Field3>
    </row>
</data>

Tried the following Code but :

Node root = new XmlParser().parse(xml);
def orderNode = root.VqlQueryRestResult;
orderNode[0].children().sort(true) {it.item.Field3.text()}

I need to reorder it as below:

<VqlQueryRestResult>
    <data>
        <row>
            <Field3>AAA</Field3>
        </row>
        <row>
            <Field3>BBB</Field3>
        </row>
        <row>
            <Field3>CCC</Field3>
        </row>
    </data>
</VqlQueryRestResult>

I would like to now sort this XML so that it goes to the correct position, please help


Solution

  • It worked with the code below:

    def root = new XmlParser().parseText(msg);
    root.data.each { it.children().sort { it.Field3.text() } }