32

We have this JAXB annotation:

 @XmlElement(name = "Strategy", required = true)
 protected List<Strategy> strategy;

If there are no Strategy elements present, no exception is thrown.. why is this? Shouldn't we get an exception?

Ryan Ransford
  • 3,224
  • 28
  • 35
Marcus Leon
  • 55,199
  • 118
  • 297
  • 429

2 Answers2

38

The JAXB reference implementation doesn't use this attribute for validation, it's purely there for documentation purposes.

If you need to validate the documents, you need to define an XML Schema, and inject it into the Marshaller or Unmarshaller, using SchemaFactory.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 1
    see [this](http://stackoverflow.com/a/2696765/12604) for an example of loading the `Schema` from your `JAXBContext` to use in the `Marshaller`/`Unmarshaller`. – Ryan Ransford Jan 25 '13 at 16:19
  • I wouldn't say it is purely for documenation - it's also used for schema generation. When you generate an XSD from your Java classes and you have `required = true` then the element declaration in the XSD will be generated with `minOccurs="1"`. You can then use the XSD for validating XML. – Jesper Sep 30 '17 at 13:18
1

Additionally, you could use the beforeMarshal and afterUnmarshal methods to validate inputs as spec'd in Marshaller and Unmarshaller.

The scheme under which these methods are accessed will also allow you to add an arbitrary throws clause to the method declaration. This means that when implementing these methods, you can safely use javax.xml.bind.MarshalException and javax.xml.bind.UnmarshalException (or whatever sort of Exception you want) to signal validation errors.

Ryan Ransford
  • 3,224
  • 28
  • 35