我需要将 POJO 序列化为 Documents ,然后将 Document 序列化为字符串。我有以下代码,
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;
}
除非项目使用 xerces,否则这似乎可行。然后objectToDOMDocument
返回带有根节点 "document:null" 的 Document 并以at DOMDocumentToString
失败。DOMSource node as this type not supported
transformer.transform(domSource, result);
我知道我可以使用DocumentBuilderFactory.newInstance(String,ClassLoader)
并传递没有此类问题的工厂名称,但我相信这应该是更好的方法....
感谢您的建议。