XOM and Canonical XML
I'm making a java application that checks if a XML file is already Canonical or not using XOM.
In my tests I have the following file which is already Canonical.
<doc xmlns="http://example.com/default" xmlns:x="http://example.com/x">
<a a1="1" a2="2">123</a>
<b xmlns:y="http://example.com/y" a3=""3"" y:a1="1" y:a2="2"></b>
</doc>
Here it is the code when I load it again with XOM.
<?xml version="1.0"?>
<doc xmlns="http://example.com/default" xmlns:x="http://example.com/x">
<a a1="1" a2="2">123</a>
<b xmlns:y="http://example.com/y" a3=""3"" y:a1="1" y:a2="2" />
</doc>
As you can see it adds again xml tag and 开发者_运维技巧delete the closing tag </b>
because the value of tag b is empty.
I haven't got any problem with xml version tag but I don't know what to do to keep the closing tag </b>
when I load the canonical document from file.
It looks like you are outputting the document with a XOM Serializer you need to use a XOM Canonicalizer to output your xml document and keep it Canonical
This gives the output:
<?xml version="1.0" encoding="UTF-8"?>
<doc xmlns="http://example.com/default" xmlns:x="http://example.com/x">
<a a1="1" a2="2">123</a>
<b a3=""3"" y:a1="1" y:a2="2" xmlns:y="http://example.com/y"/>
</doc>
The following example program will output your XML Cannonically to System.out using a XOM Canonicalizer
package com.foo.bar.xom;
import java.io.IOException;
import nu.xom.Builder;
import nu.xom.canonical.Canonicalizer;
import nu.xom.Document;
import nu.xom.ParsingException;
import nu.xom.Serializer;
import nu.xom.ValidityException;
public class App
{
public static void main(String[] args) throws ValidityException, ParsingException, IOException
{
Builder builder = new Builder();
//Serializer serializer = new Serializer(System.out);
Canonicalizer canonicalizer = new Canonicalizer(System.out, Canonicalizer.EXCLUSIVE_XML_CANONICALIZATION);
//this assumes to your xml document is on the classpath in this package as my.xml
Document input = builder.build(App.class.getResourceAsStream("my.xml"), null);
//serializer.write(input);
canonicalizer.write(input);
}
}
精彩评论