Java: XML canonicalization

20.6k views Asked by At

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

There are 2 answers

4
eolith On BEST ANSWER

The Canonicalizer class at Apache XML Security project.

Initialize the library.

org.apache.xml.security.Init.init(); 

Convert your XML.

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

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.