Search code examples
javaxmlcastor

Sorting an XML in Java


I have an XML similar to below, which needs to be sorted using the date field.

<root> 
    <Node1>
        <date></date> 
    </Node1> 
    <Node1> 
        <date></date> 
    </Node1> 
    <Node1> 
        <date></date> 
    </Node1> 
    <Node1> 
        <date></date> 
    </Node1> 
    <Node2> 
        <date></date> 
    </Node2> 
    <Node2> 
        <date></date> 
    </Node2> 
    <Node2> 
        <date></date> 
    </Node2> 
    <Node2> 
        <date></date> 
    </Node2> 
</root>

I would like to sort the XML based on the date(say ascending order), irrespective of whether the date is under Node1 or Node2. Actually, in Java code I have two separate lists, one with Node1 objects and other with Node2 objects. I can sort the list in any order separately inside java. But I need to have the dates sorted irrespective of the nodes it is appearing on the XML. What is the best approach to sort this way in Java?

Actually I am using Castor for marshaling the java objects to XML. If you know this can be done with Castor, that will be great!


Solution

  • I'd use XSLT, it has probs with sorting dates that you'll need to work round, simplest way if you can control it is to have sortable date format like yyyymmdd

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    
      <xsl:template match="root">
        <xsl:copy>
            <xsl:apply-templates>
               <xsl:sort data-type="number" select="date"/>
            </xsl:apply-templates>
        </xsl:copy>
      </xsl:template>
    
      <xsl:template match="*">
          <xsl:copy>
              <xsl:apply-templates/>
          </xsl:copy>
      </xsl:template>
    
    </xsl:stylesheet>