javaxml

Java XML library that preserves attribute order


I am writing a Java program that reads an XML file, makes some modifications, and writes back the XML.

Using the standard Java XML DOM API, the order of the attributes is not preserved.

That is, if I have an input file such as:

<person first_name="john" last_name="lederrey"/>

I might get an output file as:

<person last_name="lederrey" first_name="john"/>

That's correct, because the XML specification says that order attribute is not significant.

However, my program needs to preserve the order of the attributes, so that a person can easily compare the input and output document with a diff tool.

One solution for that is to process the document with SAX (instead of DOM): Order of XML attributes after DOM processing

However, this does not work for my case, because the transformation I need to do in one node might depend on a XPath expression on the whole document.

So, the simplest thing would be to have a XML library very similar to the standard Java DOM library, with the exception that it preserves the attribute order.

Is there such a library?

PS: Please, avoid discussing whether I should the preserve attribute order or not. This is a very interesting discussion, but it is not the point of this question.


Solution

  • You might also want to try DecentXML, as it can preserve the attribute order, comments and even indentation.

    It is very nice if you need to programmatically update an XML file that's also supposed to be human-editable. We use it for one of our configuration tools.

    -- edit --

    It seems it is no longer available on its original location; try these ones: