Skip to main content

marshalling code marshals the JAXB Object without a root element

2 replies [Last post]
Joined: 2005-11-17

The schema below results in marshalled JAXB Object without a root element:

generated (marshalled) xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

Of course unmarshalling fails with the "[org.xml.sax.SAXParseException: unexpected root element (uri:" exception.

From reading other posts it's become clear that one way to resolve this is to annotate the generated Java code with an @XmlRootElement. Indeed it works.

But - does this imply I have to edit the xjc generated code everytime I run xjc? There must be a better way, no?

thanks for any help on this...

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2003-06-25

No. There is no need to annotate the generated code with @XmlRootElement. You use the ObjectFactory method.

To be marshalled, a JAXB object must be either be an instance of a javax.xml.bind.JAXBElement or a type that has been annotated with @XmlRootElement. Otherwise, a MarshalException must be thrown. Which version of JAXB are you using ? Some of the earlier versions of JAXB-RI did not throw such an exception.

If you look at the generated code, you should see an ObjectFactory class (generated) that contains a factory method.

public JAXBElement createPatient(Patient value) {..}

So after you create an instance of Patient type, use the ObjectFactory method to create an instance of the JAXBElement instance which is what you pass to the Marshaller.marshal(..) method.

Joined: 2005-11-17

That did it! Thanks for the help. One of my problems was looking at old documentation ( which doesn't show the use of JAXBElement...

public static void main (String args[]) {
try {
JAXBContext jc = JAXBContext.newInstance("test.jaxb");
ObjectFactory objFactory = new ObjectFactory();

Unmarshaller unmarshaller = jc.createUnmarshaller();

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT ,
new Boolean(true));

Validator validator = jc.createValidator();

Collection collection= (Collection)
unmarshaller.unmarshal(new File( "books.xml"));