Having a trivial code like this:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class A {
@XmlPath("B/text()")
private String b;
@XmlPath("C/text()")
private Integer c;
...
}
It works absolutely fine as long as I have apt values in my XML. I’d like to mark the field c as required, so MOXy throw every time I try to read the document where c is either not set, or invalid. What’s the easiest solution?
Update:
Setting default values will also do.
EclipseLink JAXB (MOXy) or any JAXB implementation will not perform a set operation for missing nodes, so you could do the following:
Option #1 – Default the field value
With the following demo code:
Will produce the following output:
Option #2 – Specify defaultValue on
@XmlElementYou can specify a defaultValue on the
@XmlElementannotation, but this will only set the defaultValue when an empty element is unmarshalled.With the following demo code:
Will produce the following output:
Option #3 – Specify an XML schema on the
Unmarshallerto force validationUsing MOXy or any JAXB implementation you can set an XML schema on the Unmarshaller to have the input validated: