tags:

views:

492

answers:

4

I am trying to sort XML documents according to their nodes. What is an efficient sorting method?

+1  A: 

I am not aware of any XML parser that provides sorting of elements out of the box, since XML elements have no natural sort order. That is because in the XMl specification the sort order of elements does matter, therefore no code parsing an arbitrary chunk of XML should make any assumptions about the the order of the elements.

If you need the elements sorted you are going to have to parse the XML document using your favourite XML parser and sort them yourself. Alternatively you could sort the document using XSLT.

Tendayi Mawushe
+2  A: 

You can sort the nodes of a XML document using XSLT sort

Pierre
+1  A: 

An alternative to the XSLT approach is to write your own utility method which sorts the children of a specified node in descending or ascending order using a specified Comparator.

public static void sortChildNodes(Node node, Comparator comparator, boolean descending) {

}
dogbane
A: 

I would strongly recommend that you learn XSLT since it is very well suited for manipulating XML documents, including sorting etc. Java has good support for runing XSLT on files and in-memory structures as part of the standard runtime library.

The usage of

     <xsl:sort select="..."/>

is well described at http://www.xml.com/pub/a/2002/07/03/transform.html

Thorbjørn Ravn Andersen
Thank for your suggestion, i use java with eclipse IDE .So how to run that xsl files.
thandar
Name your XSLT files with the file type "XSL", i.e. "test.xsl".Then you can right click and choose "Run as" -> "XSL Transformation" to do an xslt transformation. From the documentation I understand that if you change the XSLT processor in the XSL preference pane to Xalan you can even debug the XSLT process.I'm using Eclipse JEE. It may not be available in the other Eclipse editions.
Thorbjørn Ravn Andersen