views:

343

answers:

1

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?

+1  A: 

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.

skaffman