Vladimir Korobkov
Vladimir Korobkov

Reputation: 619

javax.xml.transform.Transformer swaps elements attributes after transformation

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;
}

Upvotes: 0

Views: 1055

Answers (1)

David Carlisle
David Carlisle

Reputation: 5652

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.

Upvotes: 1

Related Questions