How to transform Java Document object into XML String ?
When working with org.w3c.dom.Document object in java, it is often usefull to get the XML String representation for debug.
A common way to do achieve that goal is simply to use getDocumentElement() method like this:
// Print XML Document to the output console
org.w3c.dom.Document doc = ...
System.out.println(doc.getDocumentElement());
However, in some case, according to the XML processor loaded, this method doesn't work. I was faced to this problem with Tomcat servlet container. In such case the following solution
can help a lot especially for debug.
A way to bypass the problem is to perform a "null" XSLT transformation as shown below:
public static String getXMLDocString(Document arg, ServletContext context)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String xslFilePath = context.getRealPath("default.xsl");
File xslFile = new File(xslFilePath);
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer =
tFactory.newTransformer(
new StreamSource(xslFile) );
transformer.transform(new DOMSource(arg), new StreamResult(baos));
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String res = new String(baos.toByteArray());
return res;
}
Note the use of default.xsl stylesheet, which tranform a XML file into the same XML file:
|