Java 输出文件中 XML 属性的控制顺序 [英] Control order of XML attributes in outputed file in Java

查看:33
本文介绍了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.

这篇关于Java 输出文件中 XML 属性的控制顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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