Java 输出文件中 XML 属性的控制顺序
问题描述:
如何控制 XML 属性在输出文件中的列出顺序?
How do I control the order that the XML attributes are listed within the output file?
默认情况下,它们似乎是按字母顺序排列的,我将此 XML 发送到的程序显然没有处理.
It seems by default they are getting alphabetized, which the program I'm sending this XML to apparently isn't handling.
例如我希望 zzzz
先显示,然后在下面的代码中显示 bbbbb
.
e.g. I want zzzz
to show first, then bbbbb
in the following code.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root = doc.createElement("requests");
doc.appendChild(root);
root.appendChild(request);
root.setAttribute("zzzzzz", "My z value");
root.setAttribute("bbbbbbb", "My b value");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(file));
transformer.transform(source, result);
答
我在使用 XML DOM API 写入文件时遇到了同样的问题.为了解决这个问题,我不得不使用 XMLStreamWriter
.属性按照您使用 XMLStreamWriter
编写的顺序出现在 xml 文件中.
I had the same issue when I used XML DOM API for writing file. To resolve the problem I had to use XMLStreamWriter
. Attributes appear in a xml file in the order you write it using XMLStreamWriter
.