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

2022-08-31 16:07:10

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?


答案 1

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

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


答案 2

I solved this problem by using the class as shown in the example below:ObjectFactory

PostTransaction transactionRequest = new PostTransaction();
//Some code here

JAXBElement<PostTransaction> jAXBElement = new ObjectFactory().createPostTransaction(transactionRequest);
 try {
JAXBElement<PostTransactionResponse> aXBElementResponse = (JAXBElement<PostTransactionResponse>) webServiceTemplate.marshalSendAndReceive("wsdlUrl", jAXBElement, new SoapActionCallback("soapMethodName"));

推荐