Sort xml attributes for pretty print using javax.xml.transform.Transformer

旧街凉风 提交于 2019-12-01 08:28:46

问题


Is there a way I could tell the xml transformer to sort alphabetically all the attributes for the tags of a given XML? So lets say...

<MyTag paramter1="lol" andTheOtherThing="potato"/>

Would turn into

<MyTag andTheOtherThing="potato" paramter1="lol"/>

I saw how to format it from the examples I found here and here, but sorting the tag attributes would be the last issue I have.

I was hoping there was something like:

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.SORTATT, "yes"); // <-- no such thing

Which seems to be what they say: http://docs.oracle.com/javase/1.4.2/docs/api/javax/xml/transform/OutputKeys.html


回答1:


As mentioned, by forty-two, you can make canonical XML from the XML and that will order the attributes alphabetically for you.

In Java we can use something like Apache's Canonicalizer

org.apache.xml.security.c14n.Canonicalizer

Something like this (assuming that the Document inXMLDoc is already a DOM):

Document retDoc;
byte[] c14nOutputbytes;
DocumentBuilderFactory factory;
DocumentBuilder parser;

// CANONICALIZE THE ORIGINAL DOM
c14nOutputbytes = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(inXMLDoc.getDocumentElement());

// PARSE THE CANONICALIZED BYTES (IF YOU WANT ANOTHER DOM) OR JUST USE THE BYTES
factory = DocumentBuilderFactory.newInstance();
factory.set ... // SETUP THE FACTORY
parser = factory.newDocumentBuilder();
// REPARSE TO GET ANOTHER DOM WITH THE ATTRIBUTES IN ALPHA ORDER
ByteArrayInputStream bais = new ByteArrayInputStream(c14nOutputbytes);
retDoc = parser.parse(bais);

Other things will get changed when Canonicalizing of course (it will become Canonical XML http://en.wikipedia.org/wiki/Canonical_XML) so just expect some changes other than the attribute order.



来源:https://stackoverflow.com/questions/9199739/sort-xml-attributes-for-pretty-print-using-javax-xml-transform-transformer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!