java - 编写 XML 元素时设置属性的顺序

标签 java xml

<分区>

在 java 中编写以下内容时:

Element fieldEl = targetDocument.createElement("field");
fieldEl.setAttribute("Wine","Marlo");
fieldEl.setAttribute("Beer","Corona");

添加属性的顺序不会保存在结果 XML 文件中。
我怎样才能控制 XML 元素中属性的顺序(这样人们就很容易阅读......)??

最佳答案

根据 DOM standard 没有定义属性节点的顺序:

Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.

(添加了强调)并且都不在 XML standard 中:

Note that the order of attribute specifications in a start-tag or empty-element tag is not significant.

我认为,许多 DOM 实现根本不支持属性排序。您必须编写自己的序列化机制才能实现排序(没有双关语意)。

关于java - 编写 XML 元素时设置属性的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3184598/

相关文章:

java - 在 Java 中通过类型转换分配属性值

java - 无法为跟踪文件 .lastUpdated 创建父目录

java - 使用 java 获取系统信息,即显卡、cpu、ram 等

c# - 改进在 sql server 中读取 XML 字符串

java - 无法将 Spring 应用程序解析为类型

java - hashmap在多线程环境下可以有重复的键吗

java - 从java输入流中获取xml信息

java - JAXB 编码具有相同名称的可变元素列表

xml - 使用 XSLT 根据节点数转换 XML

java - O(N) 排序算法