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?
If your class does not have an
@XmlRootElement
annotation then you can wrap it in an instance ofJAXBElement
. If you generated your classes from an XML Schema then the generatedObjectFactory
may have a convenience method for you.I have written more about this use case on my blog:
I faced same issue due to legacy wsdl that doesn't have xsd schema inside wsdl definition. I solved this issue by having two maven plugins to generate operations from wsdl as well DTD from xsd file as below and for marshalling
new ObjectFactory().createHandShake(new HandShake());
I suggest you to use maven plugin "maven-plugin-jaxb2" to generate classes from an XSD. Use a binding file *. xjb to add annotations @XmlRootElement.
Following some example
e.g Binding file
e.g Maven Plugin
http://confluence.highsource.org/display/MJIIP/User+Guide