Wednesday, February 01, 2012

JAXB - Unmarshal non root element

While generating JAX-WS web service client code using wsimport, it generates Object factory top level method input and output type. This restricts the use to marshal and unmarshal classes which are contained within the top level objects.

More often than not, top level Schema objects are non-domain specific objects like MethodInput/MethodOutput. You can unmarshal them using ObjectFactory


But if you want to unmarshal XML chunks of objects contained within those top level object, the same approach does not work, if those generated classes are not included as part of ObjectFactory or they do not have annotation @XmlRootElement on top of that.


Option 1
So the obvious option is to add @XmlRootElement to any generated classes that you want to unmarshal directly, but when you are using wsdls are from an external source, idea of updating generated classes breaks the process. 

Option 2
Another option is to pass the child element's Node object to unmarshal 



Anonymous said...

thanks men - good post

Anonymous said...

thanks man - option 2 was very helpful for me

Anonymous said...

I have 2 xsd files
Element from XSD A

element from XSD B

When I try to marshal "LifeObj" EXception I am getting is

[com.sun.istack.internal.SAXException2: unable to marshal type "packagebname.ProcessParameters" as an element because it is missing an @XmlRootElement annotation]

Code i am using is

ProcessParameters parametersType = new ProcessParameters();
ExtensionObj eExtensionType = new ExtensionObj();

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
File SEEC_Life_xsd = new File("xsd/Life.xsd");
Schema schema = schemaFactory.newSchema(Life_xsd);
JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

marshaller.marshal(new JAXBElement(new QName(url,"ExtensionObj"), ExtensionObj.class, eExtensionType), System.out);

Anonymous said...

Thanks, this was the post that finally solved my problem!