保留属性顺序的java xml库 [英] java xml library that preserves attribute order

查看:33
本文介绍了保留属性顺序的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.

这篇关于保留属性顺序的java xml库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆