Java: XML canonicalization

倾然丶 夕夏残阳落幕 提交于 2019-11-27 12:26:31

问题


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

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>

回答1:


The Canonicalizer class at Apache XML Security project:

Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
byte canonXmlBytes[] = canon.canonicalize(yourXmlBytes);
String canonXmlString = new String(canonXmlBytes);



回答2:


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



来源:https://stackoverflow.com/questions/5117610/java-xml-canonicalization

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