0

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.

a1ex07
  • 36,826
  • 12
  • 90
  • 103
  • 1
    If you are wanting to map POJOs to XML, you really want to be using JAXB. See: http://stackoverflow.com/questions/607141/what-is-jaxb-and-why-would-i-use-it – young.fu.panda Jul 15 '12 at 15:49
  • @young.fu.panda: At the current moment I'm trying not to use any extra libraries unless it's absolutely mandatory. I was thinking about JAXB, but it seems to be overkill for such a simple task... – a1ex07 Jul 15 '12 at 15:55
  • 1
    JAXB is part of core Java and uses no external libraries. I don't see why you would think it is heavier weight than what you're currently doing. – Hovercraft Full Of Eels Jul 15 '12 at 16:54

0 Answers0