Output a DOM Document as XML using Java

WordPress database error: [Got error 28 from storage engine]
SHOW FULL COLUMNS FROM `markjacobsen_options`

WordPress database error: [Got error 28 from storage engine]
SHOW FULL COLUMNS FROM `markjacobsen_options`

WordPress database error: [Got error 28 from storage engine]
SHOW FULL COLUMNS FROM `markjacobsen_options`

Ok, here’s another nerdy post for all the java developers out there.  Hopefully it saves you some time.

Let’s say you have a XML DOM Document that you’ve been modifying in your code, and now want to write it back out as XML.  One would think there would be a nice toXml() method or something on the Document, but there isn’t.  Instead, make sure you have the xalan.jar file on your class path and use this function…


public static String getDomDocumentAsXml(org.w3c.dom.Document domDocument)
{
	try
	{
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		StreamResult xmlOutput = new StreamResult(new StringWriter());
		transformer.transform(new DOMSource(domDocument), xmlOutput);
		return xmlOutput.getWriter().toString();
	}
	catch (Exception e) { e.printStackTrace(); return null; }
}
Like this? Consider joining my mailing list, or at least using my affiliate link when buying from Amazon 🙂

You or someone you know looking to buy or sell?

WordPress database error: [Got error 28 from storage engine]
SHOW FULL COLUMNS FROM `markjacobsen_options`

WordPress database error: [Got error 28 from storage engine]
SHOW FULL COLUMNS FROM `markjacobsen_options`

WordPress database error: [Got error 28 from storage engine]
SHOW FULL COLUMNS FROM `markjacobsen_options`

WordPress database error: [Got error 28 from storage engine]
SHOW FULL COLUMNS FROM `markjacobsen_options`

WordPress database error: [Got error 28 from storage engine]
SHOW FULL COLUMNS FROM `markjacobsen_options`

WordPress database error: [Got error 28 from storage engine]
SHOW FULL COLUMNS FROM `markjacobsen_options`

Leave a Reply