tags:

views:

248

answers:

1

Currently I am using Castor framework to marshall the object into xml file it work greats

Writer writer = new FileWriter("D:/out.xml");
Marshaller.marshal(test, writer);

But now I am using javax.xml.bind to do the same thing.

            Writer writer = new FileWriter("D:/out.xml");
        JAXBContext context =
            JAXBContext.newInstance(test.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(test, writer);

Then I hits this error message :

unable to marshal type "package1.Testing" as an element because it is missing an @XmlRootElement annotation]

+2  A: 

Add the XmlRootElement annotation and you won't get the error anymore. This should be added to the top-level or "root" class.

Taylor Leese
Thanks for your answer can you roughly explain to me why using castor is okay but jaxb need to add in XmlRootElement
It's just semantics. The Castor and JAXB API's are different and JAXB requires the annotation whereas Castor doesn't.
Taylor Leese
Does it mean JAXB need to know which class to look at so in my Testing file i have to put in @XmlRootElement?
The class that is "test" is your example should have @XmlRootElement.
Taylor Leese
I know to add in the @XmlRootElement just want to know the reason why need to add in. Thanks for your answer I solved the problem
The reason is because that's how JAXB figures out name of root element. This is only needed for root element since properties use field/getter/setter name to determine element name; but this is not available for root. I guess Castor defaults to using class name or soemthing else, but JAXB requires explicit definition.
StaxMan