使用 javax.xml.transform.Transformer 对 xml 属性进行排序以实现漂亮的打印
有没有办法告诉 xml 转换器按字母顺序对给定 XML 标签的所有属性进行排序?所以可以说...
<MyTag paramter1="lol" andTheOtherThing="potato"/>
会变成
<MyTag andTheOtherThing="potato" paramter1="lol"/>
我看到如何从我找到的示例中格式化它 此处 和 此处,但对标签属性进行排序将是我遇到的最后一个问题。
我希望有类似的东西:
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.SORTATT, "yes"); // <-- no such thing
他们似乎是这么说的: http://docs.oracle。 com/javase/1.4.2/docs/api/javax/xml/transform/OutputKeys.html
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如前所述,到了 42 岁,您可以从 XML 生成规范 XML,这将按字母顺序对属性进行排序。
在 Java 中,我们可以使用 Apache 的 Canonicalizer
org.apache.xml.security.c14n.Canonicalizer
之类的东西(假设 XMLDoc 中的文档已经是 DOM):
当然,在规范化时,其他内容也会发生变化(它将成为 Canonical XML) http://en.wikipedia.org/wiki/Canonical_XML),因此除了属性顺序之外,还需要进行一些更改。
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):
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.