Monday, April 14, 2008

Efficient XML creation with well-formedness support

After analyzing lot of points (with a discussion in the thread, "Best way to create an XML document" on xml-dev list) for creating XML document from scratch, I concluded that the following technique is perhaps the most efficient way to do this (with well-formedness support):

public static void main(String[] args) {
try {
TransformerFactoryImpl tfi = new TransformerFactoryImpl();
TransformerHandler tHandler = tfi.newTransformerHandler();

tHandler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
String output = "output.xml";
tHandler.setResult(new StreamResult(new File(output)));

tHandler.startDocument();
tHandler.startElement("", "x", "x", null);
AttributesImpl attrs = new AttributesImpl();
attrs.addAttribute("", "attr1","attr1", "", "123");
attrs.addAttribute("", "attr2","attr2", "", "456");
tHandler.startElement("", "y", "y", attrs);
tHandler.startElement("", "z", "z", null);
tHandler.endElement("", "z", "z");
tHandler.endElement("", "y", "y");
tHandler.endElement("", "x", "x");
tHandler.endDocument();

if (isWellFormed(output)) {
/*
do something with the generated file
*/
}
else {
System.out.println("Generated XML document is not well-formed.");
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}

private static boolean isWellFormed(String output) {
try {
XMLReaderAdapter xra = new XMLReaderAdapter();
InputSource is = new InputSource(new FileInputStream(output));
xra.parse(is);
return true;
}
catch(Exception ex) {
return false;
}
}

I also agree to this opinion:
Since version 1.6, Java has supported the javax.xml.stream package, so the most straightforward way would be to use an XMLStreamWriter.

Please note: javax.xml.stream API is available to previous versions of Java through JSR 173 (https://sjsxp.dev.java.net/)

Acknowledgements
Martin Gallagher
Alain Couthures
Michael Kay
Robert Koberg
Andrew Welch
Michael Glavassevich
Chris Burdess

No comments: