Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB validation using annotations

If I have a simple class such as:-

@XmlRootElement public class MyClass {    @XmlAttribute(required=true)    private String myattribute } 

Is it possible to validate a corresponding xml document WITHOUT an xml schema i.e. using only the annotations?

like image 805
Martin Avatar asked Mar 02 '10 18:03

Martin


People also ask

How do I disable schema validation in JAXB?

To turn off the schema validation you should set the schema-validation-enabled property to false .

How do you ignore a field in XML response?

Ignore XML Attribute. You can specify ignore="true" or ignore="false". The default value is false. Specifying ignore="false" has no effect on the attribute value assigned when an object of the type specified in the rule is created and no effect on the constraints.

How XSD is used in Java?

xsd is the XML schema you will use as input to the JAXB binding compiler, and from which schema-derived JAXB Java classes will be generated. For the Customize Inline and Datatype Converter examples, this file contains inline binding customizations.


1 Answers

Good question. As far as I know, the required attribute is generated by XJC when it finds a non-optional schema type, and I think it's also used by the schema generator. At runtime, though, it's not used for anything, serving no other purpose than a documentary annotation.

One thing you could consider is the JAXB runtime's callback options. In this case, you could just define a afterUnmarshal() method on MyClass which programmatically validates the state of the object, throwing an exception if it doesn't like it. See the above link for other options, including registering separate validator classes.

Having said that, validation against a schema really is the best way. If you don't have one, you should considering writing one. The schemagen tool can generate a schema from your object model, which you can then modify to add whatever constraints you like. Hopefully, schemagen will generate mandatory schema elements from your required=true class fields.

like image 143
skaffman Avatar answered Sep 22 '22 15:09

skaffman