Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java XML library that preserves attribute order

Tags:

java

xml

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.

like image 769
David Portabella Avatar asked Jul 18 '13 14:07

David Portabella


People also ask

Does XML maintain order?

XML element comparison by default preserves the order of elements in the two documents.

Are XML attributes ordered?

XML attributes are re-ordered alphabetically by the DOM parser. Attributes are being displayed in alphabetical order suggesting that the parser is sorting them.


2 Answers

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:

  • https://github.com/cartermckinnon/decentxml
  • https://github.com/haroldo-ok/decentxml (unnoficial and unmaintained fork; kept here just in case the other forks disappear, too)
  • https://directory.fsf.org/wiki/DecentXML
like image 189
Haroldo_OK Avatar answered Nov 14 '22 02:11

Haroldo_OK


Do it twice:

Read the document in using a DOM parser so you have references, a repository, if you will.

Then read it again using SAX. At the point where you need to make the transformation, reference the DOM version to determine what you need, then output what you need in the middle of the SAX stream.

like image 29
Bob Dalgleish Avatar answered Nov 14 '22 03:11

Bob Dalgleish