cancel
Showing results for 
Search instead for 
Did you mean: 

Parse XML based on a field

Former Member
0 Kudos

Hello SDN,

I have a input XML say

<?xml version="1.0" encoding="UTF-8" ?> 
<ns0:MT_SND_TEST xmlns:ns0="http://test.com">
<Record>
<Id>5310</Id>
<Name>Rob</Name>
</Record>
<Record>
<Id>0001</Id>
<Name>Mani</Name>
</Record>
<Record>
<Id>7012</Id>
<Name>Ashwin</Name>
</Record>
</ns0:MT_SND_TEST>

I need to sort this XML based on Id field so that the target XML looks like

<?xml version="1.0" encoding="UTF-8" ?> 
<ns0:MT_SND_TEST xmlns:ns0="http://test.com">
<Record>
<Id>0001</Id>
<Name>Mani</Name>
</Record>
<Record>
<Id>5310</Id>
<Name>Rob</Name>
</Record>
<Record>
<Id>7012</Id>
<Name>Ashwin</Name>
</Record>
</ns0:MT_SND_TEST>

I am planning to use DOM parser for this. Is there any function in standard DOM API to achieve this? If not, kindly let me know the steps that will be needed in implenting this.

Thank You.

Regards,

Jai Shankar

Accepted Solutions (0)

Answers (1)

Answers (1)

oliver
Product and Topic Expert
Product and Topic Expert
0 Kudos

Hi Jai,

just did a quick lookup. As far as I know there is no sort functionality but you have to use XSLT.

http://www.programmersheaven.com/2/FAQ-XML-Sort-XML-Dynamically

Hope it helps you.

Regards,

ok

Former Member
0 Kudos

Hi Oliver,

Thanks. But my requireiement is to achieve this with in Java.

Regards,

Jai Shankar

Former Member
0 Kudos

> Thanks. But my requireiement is to achieve this with

> in Java.

Hello Jai,

unfortunately, the standard DOM API does not provide "direct" sorting functionality. However, you may be able to write your own java.util.Comparator and use the java.util.Collections.sort() method for this task.

If you are using JDOM, then here's some sample code on how to do this:

http://www.junlu.com/msg/243530.html

Regards,

Jens

ravi_raman2
Active Contributor
0 Kudos

This is what i would suggest,

First use Dom to get the org.w3c.dom.Element to get getElementsByTagName(), the tag being ID..once you have a list sort the list and then for each id after sorting...traverse the tree and reconstruct the values, u can use getNodeName()...but essence is to get the value of the id and then push that into a sorted list then create the xml back...

Hope that helps

Regards

Ravi Raman