Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to marshal type as an element because it is missing an @XmlRootElement annotation for auto generated classes

I need to validate Class object against my schema in which I have provided regular expression to validate fields for auto generated JAXB classes. When I try to validate my class object I get below error:

unable to marshal type "xyz" as an element because it is missing an @XmlRootElement annotation

Here is the code that I use to validate my autogenerated class object:

jc = JAXBContext.newInstance(obj.getClass()); source = new JAXBSource(jc, obj); Schema schema = schemaInjector.getSchema(); Validator validator = schema.newValidator(); validator.validate(source); 

Is there any other way I can solve this?

like image 616
user656213 Avatar asked Jul 01 '14 21:07

user656213


People also ask

What is @XmlRootElement in Java?

When a top level class or an enum type is annotated with the @XmlRootElement annotation, then its value is represented as XML element in an XML document. This annotation can be used with the following annotations: XmlType , XmlEnum , XmlAccessorType , XmlAccessorOrder .

What is the use of ObjectFactory in JAXB?

jaxb package. An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content. The Java representation of XML content can consist of schema derived interfaces and classes representing the binding of schema type definitions, element declarations and model groups.


1 Answers

If your class does not have an @XmlRootElement annotation then you can wrap it in an instance of JAXBElement. If you generated your classes from an XML Schema then the generated ObjectFactory may have a convenience method for you.

I have written more about this use case on my blog:

like image 163
bdoughan Avatar answered Oct 14 '22 10:10

bdoughan