<分区>
在 java 中编写以下内容时:
Element fieldEl = targetDocument.createElement("field");
fieldEl.setAttribute("Wine","Marlo");
fieldEl.setAttribute("Beer","Corona");
添加属性的顺序不会保存在结果 XML 文件中。
我怎样才能控制 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/