2

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

4
  • Can you show us what your xml document looks like and how you want it sorted? Commented 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? Commented 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. Commented Dec 11, 2009 at 8:58
  • possible duplicate of Sorting an XML in Java Commented May 7, 2013 at 9:21

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

}

Comments

1

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

Comments

0

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

2 Comments

Thank for your suggestion, i use java with eclipse IDE . So how to run that xsl files.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.