将Java对象序列化为XML字符串

时间:2012-07-15 15:34:56

标签: java xml-serialization

我需要将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,而DOMDocumentToStringDOMSource node as this type not supported处的transformer.transform(domSource, result);失败。

我知道我可以使用DocumentBuilderFactory.newInstance(String,ClassLoader)并传递没有此类问题的工厂名称,但我相信它应该是更好的方式....

感谢您的建议。

0 个答案:

没有答案