Java:XML 规范化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5117610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:31:58  来源:igfitidea点击:

Java: XML canonicalization

javaxmlcanonicalization

提问by Ivan

What's the easiest way to make a canonical form of a XML file in Java? Do you have some done code for that? I've found several links on the net, like this, this, and this, but I can't make it to work :/

在 Java 中制作规范形式的 XML 文件的最简单方法是什么?你有一些完成的代码吗?我在网上找到了几个链接,比如这个这个这个,但我不能让它工作:/

Thanks,

谢谢,

Ivan

伊万

EDIT: I used the canonicalizer that was proposed down there, but I get strange results. To be more precize, this method doesn't delete white spaces between elements... This is what I get:

编辑:我使用了那里提出的规范化程序,但我得到了奇怪的结果。更准确地说,此方法不会删除元素之间的空格......这就是我得到的:

<Metric xmlns="http://www.ibm.com/wsla" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="total_memory_consumption_metric" type="double" unit="Mbit" xsi:schemaLocation="http://www.ibm.com/wsla WSLA.xsd">                        <Source>ServiceProvider</Source>                        <MeasurementDirective resultType="double" xsi:type="StatusRequest">                              <RequestURI> ***unused*** </RequestURI>                        </MeasurementDirective>                  </Metric>

回答by eolith

The Canonicalizerclass at Apache XML Security project:

Apache XML Security 项目中Canonicalizer类:

org.apache.xml.security.Init.init(); // 
Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
byte canonXmlBytes[] = canon.canonicalize(yourXmlBytes);
String canonXmlString = new String(canonXmlBytes);

回答by David Moles

Another option is nu.xom.canonical.Canonicalizerif you're using XOM, or if you don't otherwise have a need for Apache XML Security.

如果您正在使用 XOM,或者如果您不需要 Apache XML 安全性,则另一个选择是nu.xom.canonical.Canonicalizer