Monday, August 31, 2009

How to save an XML file in Java and Eclipse

One problem I faced today was saving the content of an XML document (org.w3c.dom.Document) to a newly created file.
The file I was outputting to was an Eclipse abstraction (precisely org.eclipse.core.resources.IFile) of a regular one and the method offered by this IFile for setting its contents is "IFile.setContents(InputStream source, boolean force, boolean keepHistory, IProgressMonitor monitor)".
I needed to bridge the gap between that org.w3c.dom.Document and the InputStream required by "IFile.setContents()", and here's the way I did it:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

try
{
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();

transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

PrintWriter writer =
new PrintWriter(outputStream);

transformer.transform(new DOMSource(document),
new XMLWriter(writer).toXMLResult());

writer.flush();
}
catch (TransformerConfigurationException exc)
{
// DEBUG
exc.printStackTrace();
}
catch (TransformerException exc)
{
// DEBUG
exc.printStackTrace();
}
InputStream source = new ByteArrayInputStream(outputStream.toByteArray());

The main classes being used here are from package "javax.xml.transform", with the method "Transformer.transform(javax.xml.transform.dom.Source source, Result result)" basically taking care of all the stuff.

I'm going to package this one into a library called "LifeSavingUtilities"...