I need to serialize POJOs to Documents , and then Document to string. I have the following code,
public static String DOMDocumentToString(Document doc) throws TransformerException
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
writer.flush();
return writer.toString();
}
public static <T> Document objectToDOMDocument (T object) throws ParserConfigurationException, IOException, SAXException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.newDocument();
ByteArrayOutputStream st = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(st);
encoder.writeObject(object);
encoder.close();
String tmp = st.toString();
Document doc = builder.parse(new InputSource(new StringReader(tmp)));
return doc;
}
That seems to work unless the project uses xerces. Then objectToDOMDocument
returns Document with root node "document:null" and DOMDocumentToString
fails with DOMSource node as this type not supported
at transformer.transform(domSource, result);
.
I know I can use DocumentBuilderFactory.newInstance(String,ClassLoader)
and pass factory name that does not have such problem, but I believe it should be better way....
Thanks for your suggestions.