« Return to Thread: Best practices for modularity?

Re: Best practices for modularity?

by polly.c.chang :: Rate this Message:

Reply to Author | View in Thread

Hi Blaise,

Blaise Doughan wrote:
If you want to use a different root element, you can wrap
your object in an instance of org.eclipse.persistence.oxm.XMLRoot of
javax.xml.bind.JAXBElement (if your are using JAXB).
OK, I Googled the JAXB API and experimented.  I think you're saying that I need to do this:

    public Object fromXML(final File file) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(MyGenericObject.class.getPackage().getName());
        Unmarshaller u = jc.createUnmarshaller();
   
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(file);
        Element  rootElem = doc.getDocumentElement();

        JAXBElement<MyGenericObject> jaxbElem = u.unmarshal( rootElem, MyGenericObject.class);
        return jaxbElem.getValue();
    }
   
    public String toXML(final MyGenericObject obj) throws Exception {        
        JAXBContext jc = JAXBContext.newInstance(MyGenericObject.class.getPackage().getName());
        Marshaller m = jc.createMarshaller();
        JAXBElement jaxbElem = new JAXBElement(
         new QName("http://www.foo.com/bar/baz","RootNodeFoo"),
         MyGenericObject.class, obj);
        StringWriter writer = new StringWriter();
        m.marshal(jaxbElem, writer );
        return writer.toString();
    }

Is that right?  This seems a bit messy.  It's not nearly as elegant as the generic marshalling and unmarshalling code that I'm able to use with EclipseLink.  :(  Is this what you recommend?

Thanks,
Polly

 « Return to Thread: Best practices for modularity?