0

I'm trying to open XML file, add some changes, and save to other XML file result. I'm using standard javax.xml.parsers.* and javax.xml.transform* classes.

But in saved documents, attributes in some elements are swapped, for example:

Was:

<affiliation xml:id="curr1" countryCode="HU">

And after transformation:

<affiliation countryCode="HU" xml:id="curr1">

Elements "countryCode" and "xml:id" are swapped.

Is any ways to restrict such attributes swapping?

Code of opening/saving XML:

// Imports
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;    


// Opening
Document document = getDocumentBuilder().parse(src);

// Saving
getTransformer().transform(new DOMSource(document), new StreamResult(dst));

private DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
    return documentBuilder == null ? documentBuilder = documentBuilderFactory.newDocumentBuilder() : documentBuilder;
}

private Transformer getTransformer() throws TransformerConfigurationException {
    return transformer == null ? transformer = transformerFactory.newTransformer() : transformer;
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • I don't know if there is a way, but why bother? If for instance you worry about comparing files later, then use a good XML compare tool like Altova DiffDog, which can ignore attribute order. – Maestro13 Apr 28 '12 at 10:41
  • a duplicate of http://stackoverflow.com/questions/726395/order-of-xml-attributes-after-dom-processing – Pavel Veller Apr 28 '12 at 11:27
  • There is no such thing in the XML Infoset (the XPath 1.0 data model) as "order of attributes". The order in which they are serialized, depends on the implementation of the XSLT processor. However, if you show us (the smalest possible) your XSLT code and (the smalest possible) XML document so that the reported result could be reproed independently, then it might be possible to suggest refactoring that might result in other order of the serialized attributes. – Dimitre Novatchev Apr 28 '12 at 13:41
  • 1
    I found a way to fix this problem - I'm using 3d-party XML processing library - http://code.google.com/p/decentxml/ – Vladimir Korobkov May 04 '12 at 07:37

1 Answers1

1

No, attribute order in XML is not significant and XSLT explicitly allows the system to report the attributes in any order, and gives no control over the order that the attributes are serialised.

David Carlisle
  • 5,582
  • 1
  • 19
  • 23