0

I'd like to construct a org.w3c.dom.Document from my marshalled object.

I've tried what's described in this topic but in vain.

This is my code :

public Document serialise() throws Exception {
    MyClass myObjectToMarshall = this.getObjectToMarshall();
    JAXBContext jc = JAXBContext.newInstance(MyClass.class);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    m.marshal(myObjectToMarshall , System.out);
    StringWriter xml = new StringWriter();
    m.marshal(myObjectToMarshall , xml);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new InputSource(new StringReader(xml.toString())));
}

When this instruction m.marshal(myObjectToMarshall , System.out); is executed, I get the following result :

<myObjectToMarshall >
    <id>15</id>
    <code>MY_CODE</code>
    <label>MY_LABEL</label>
    <date>2015-09-15+02:00</date>
</myObjectToMarshall >

I guess the marshalling of myObjectToMarshall has been correctly done.

But, when I debug the last instruction using IntelliJ, builder.parse(new InputSource(new StringReader(xml.toString()))), I get a null Document : [#document: null]

Is there other properties to set?

Please could you help me to undestand why document is null?

Thank you in advance.

P.S. I'm using java 7.

Community
  • 1
  • 1
OHA
  • 15
  • 7

1 Answers1

1

You Document is fine.

The toString() method is implemented to return "["+getNodeName()+": "+getNodeValue()+"]". The nodeName of a document is #document, and the nodeValue of a document is null. See the javadoc of Node.

If you want a DOM document, don't marshal into a String and then parse the text. Just marshal straight into a DOM tree:

public Document serialise() throws Exception {
    MyClass myObjectToMarshall = this.getObjectToMarshall();
    JAXBContext jc = JAXBContext.newInstance(MyClass.class);
    DOMResult domResult = new DOMResult();
    jc.createMarshaller().marshal(myObjectToMarshall, domResult);
    return (Document)domResult.getNode();
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Thank you Andreas for you answer. Y're right it works very fine. I've parsed Document's node list. They are all there. – OHA Sep 16 '15 at 07:29