I am trying to sort XML documents according to their nodes. What is an efficient sorting method?
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.
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) {
}
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