thandar
thandar

Reputation: 51

How to sort XML elements in Java?

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

Upvotes: 2

Views: 10187

Answers (4)

Tendayi Mawushe
Tendayi Mawushe

Reputation: 26118

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 order of the elements.

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

Upvotes: 3

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

Upvotes: 0

dogbane
dogbane

Reputation: 274602

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) {

}

Upvotes: 2

Pierre
Pierre

Reputation: 35246

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

Upvotes: 1

Related Questions