This seems like a newbie post about XML, but the actual story is not that much simple, until DOM L3 there is no interfaces define for DOM serialization, developers use various interfaces provide by each parser vender like Xerces, Crimson….. etc . Here I have listed some of the available options that I evaluated recently.
1.) Apache Serializer
This is one of the most popular method for DOM serialization, it works fine, only problem is you need have apache Serliaztion.jar as a dependency , you don’t have any JAXP API for this .
OutputFormat format;
OutputStream out;
XMLSerializer serializer = new XMLSerializer(out, format);
Document doc;
serializer.serialize(doc);
2.) JAXP transformation
JAXP transformation can be used to DOM serialization and possible call transformer though java.xml.transformer package, when you don’t want to have any parser as dependency this is a good option. When you have a parser on classpath it loads parser specific transformer class. For Xalan it loads org.apache.xalan.transformer.TransformerIdentityImpl class, for Saxon it loads net.sf.saxon.IdentityTransformer class, when there is no parser available it uses com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl class that shipped with Sun JAXP. But if you have very large XML file you may have to think about performance.
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer;
OutputStream out;
try {
transformer = transformerFactory.newTransformer(); transformer .transform(new DOMSource(doc), new
StreamResult(out));
}
3.) DOM Level3 load/save API.
This is a very recent improvement of DOM, through LSSerializer you can serialize your DOM .but still most of parsers does not supports for this , fortunately Xerces -J supports for this , so you can call Xerces serialization through this API without any problem .
Document doc;
DOMImplementationLS DOMiLS = null;
if ((doc.getFeature("Core", "3.0") != null)
&& (doc.getFeature("LS", "3.0") != null)) {
DOMiLS = (DOMImplementationLS) (doc.getImplementation()).getFeature(
"LS", "3.0");
System.out.println("[Using DOM Load and Save]");
} else {
System.out.println("[DOM Load and Save unsupported]");
System.exit(0);
}
// get a LSOutput object
LSOutput LSO = DOMiLS.createLSOutput();
// setting the location for storing the result of serialization
try {
LSO.setByteStream((OutputStream) System.out);
} catch (Exception e) {
System.err.println(e.getMessage());
}
// get a LSSerializer object
LSSerializer LSS = DOMiLS.createLSSerializer();
// do the serialization
boolean ser = LSS.write(doc, LSO);
}
0 comments:
Post a Comment