保留属性顺序的java xml库

保留属性顺序的java xml库

问题描述:

我正在编写一个Java程序,该程序读取xml文件,进行一些修改并写回xml.

I am writing a java program that reads a xml file, makes some modifications, and writes back the xml.

使用标准的Java xml DOM api,不会保留属性的顺序.也就是说,如果我有一个输入文件,例如:

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"/>

是正确的,因为XML规范指出order属性并不重要.

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.

一种解决方案是使用SAX(而不是DOM)处理文档: DOM处理后XML属性的顺序

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

但是,这不适用于我的情况,因为我需要在一个节点中进行的转换可能取决于整个文档的XPATH表达式.因此,最简单的方法是拥有一个与标准Java DOM库非常相似的xml库,不同之处在于它保留了属性的顺序.

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 lib, with the exception that it preservers attribute order.

有没有这样的图书馆?

ps:请避免讨论我是否应该保留属性顺序.这是一个非常有趣的讨论,但这不是这个问题的重点.

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

您可能还想尝试

You might also want to try DecentXML, as it can preserve attribute order, comments and even identation. Very nice if you need to programmatically update a XML file that's also supposed to be human-editable. We use it for one of our configuration tools.