Doug Doug - 9 months ago 81
Java Question

Control order of XML attributes in outputed file in Java

How do I control the order that the XML attributes are listed within the output file?

It seems by default they are getting alphabetized, which the program I'm sending this XML to apparently isn't handling :-P.

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");
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);

Answer Source

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.