本文介绍了使用javax.xml.transform.Transformer为漂亮打印排序xml属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法告诉xml转换器按字母顺序排列给定XML标签的所有属性?所以我们说...

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"/>

会变成

<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.

我希望有类似的东西:

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

推荐答案

如上所述,到42时,您可以从XML中生成规范XML,并按字母顺序为您排序属性。

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

在Java中,我们可以使用Apache的Canonicalizer之类的东西。

In Java we can use something like Apache's Canonicalizer

org.apache.xml.security.c14n.Canonicalizer

org.apache.xml.security.c14n.Canonicalizer

这样的事情(假设文件inXMLDoc已经是DOM):

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

其他事情会在规范化时改变(它将成为Canonical XML )所以只需要一些属性顺序以外的变化。

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.

这篇关于使用javax.xml.transform.Transformer为漂亮打印排序xml属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:21