Java – JAXB generates simple types without restrictions
I am generating my first JAXB data binding I have a schema that contains an XS: simpletype:
<xs:simpleType name="NINumberType"> <xs:restriction base="xs:string"> <xs:pattern value="[A-Z]{2}\d{6}[A-D]{0,1}"/> </xs:restriction> </xs:simpleType>
In my binding I have this in xJB:
<jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" jxb:extensionBindingPrefixes="xjc"> <jxb:bindings schemaLocation="mySchema.xsd" node="/xs:schema"> <jxb:globalBindings mapSimpleTypeDef="true" /> <jxb:schemaBindings> <jxb:package name="com.company.jaxb.mySchema"/> </jxb:schemaBindings> </jxb:bindings> </jxb:bindings>
Then, through eclipse (RAD 7.5), I right-click the pattern and select generate - > java This produces the expected data binding object, but the ninumbertype has no built-in restrictions:
/** * <p>Java class for NINumberType simple type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * <simpleType name="NINumberType"> * <restriction base="{http://www.w3.org/2001/XMLSchema}string"> * <pattern value="[A-Z]{2}\d{6}[A-Z]{0,1}"/> * </restriction> * </simpleType> * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "NINumberType",propOrder = {"value"}) public class NINumberType { @XmlValue protected String value; public String getValue() {return value;} public void setValue(String value) {this.value = value;} }
Apart from the class level Javadoc, there is no mention of the regular expression restrictions specified in my schema JAXB seems to have the information needed to generate restricted code, but it is not used Can anyone help me ensure that restricted code is generated so that attempts to bind malformed Ni numbers fail?
Solution
JAXB does not generate these restrictions in the Java model If you want to enforce this constraint during conversion to or from XML, you can specify javax. XML on marshaler / unmarshaller xml. validation. An instance of schema
For more information
> http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html > http://blog.bdoughan.com/2010/11/validate-jaxb-object-model-with-xml.html
You may be able to find constraints for validation using xjc extensions such as JSR - 303 The following links may be helpful:
> https://www.java.net//forum/topic/glassfish/metro-and-jaxb/jaxb-plugin-generate-bean-validation-annotations-jsr-303