users@jaxb.java.net

unmarshall an object from a org.w3c.dom.Document object

From: David Portabella <david.portabella_at_EPFL.CH>
Date: Tue, 18 Mar 2003 11:18:46 -0700

I have problems unmarshalling an object from a org.w3c.dom.Document object.

I create a simple org.w3c.dom.Document object, and then I try to
unmarshall it, but it reports this error:

>Exception in thread "main" java.lang.NullPointerException
> at com.sun.xml.bind.unmarshaller.SAXUnmarshallerHandlerImpl.startElement
>(SAXUnmarshallerHandlerImpl.java:87)
> at com.sun.xml.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:109)
> at com.sun.xml.bind.unmarshaller.DOMScanner.parse(DOMScanner.java:64)
> at com.sun.xml.bind.unmarshaller.UnmarshallerImpl.unmarshal(Unmarshaller
>Impl.java:149)
> at TestB.createObject(TestB.java:39)
> at TestB.main(TestB.java:19)

But, if I create the same Document object, I save it into a file,
and I reload it from this file, having again a Document object
(which should be the same),
then I can unmarshall it successfully.

What can be the problem?



-----------------------------------------
import org.xml.sax.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.Marshaller;


public class TestB
{
 public static void main(String[] args) throws Exception
 {
  Document doc = createDoc();
  System.out.println(doc.getDocumentElement());
  //doc = saveAndReload(doc); //If I do this strange thing, then it works
  createObject(doc);
 }

 static Document createDoc() throws Exception
 {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setNamespaceAware(true);
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.newDocument();

  Element element = doc.createElement("WozRequest");
  element.setAttribute("action", "value");
  doc.appendChild(element);
  return doc;
 }

 static void createObject(Document doc) throws Exception
 {
  JAXBContext jc = JAXBContext.newInstance("wozObject.request");
  Unmarshaller u = jc.createUnmarshaller();
  Object o = u.unmarshal( doc );
 }

 static Document saveAndReload(Document doc) throws Exception
 {
  String fileName = "root.xml";
  PrintWriter out = new PrintWriter(new FileWriter(fileName, false));
  out.println(doc.getDocumentElement());
  out.close();

  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setNamespaceAware(true);
  DocumentBuilder db = dbf.newDocumentBuilder();
  doc = db.parse(new File(fileName));
  return doc;
 }
}
-----------------------------------------

Regards,
David