I am trying to sort XML documents according to their nodes. What is an efficient sorting method?
-
Can you show us what your xml document looks like and how you want it sorted?dogbane– dogbane2009-11-14 08:30:27 +00:00Commented Nov 14, 2009 at 8:30
-
Are you outputting the document, or you have a ready document and have to output it? Is the structure flat? Do you want to sort only top-level nodes? By what criteria - node name, attributes, node contents?Bozho– Bozho2009-11-14 08:31:08 +00:00Commented Nov 14, 2009 at 8:31
-
I means that i want to sort xml elements in java. For example, in a bibliographic data, xml document is sorted by "title" elements/nodes.thandar– thandar2009-12-11 08:58:33 +00:00Commented Dec 11, 2009 at 8:58
-
possible duplicate of Sorting an XML in Javafglez– fglez2013-05-07 09:21:49 +00:00Commented May 7, 2013 at 9:21
4 Answers
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.
Comments
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