Does JAXB support xsd:restriction?

痞子三分冷 提交于 2019-11-26 08:16:47

问题


<xs:element name=\"age\">
  <xs:simpleType>
    <xs:restriction base=\"xs:integer\">
      <xs:minInclusive value=\"0\"/>
      <xs:maxInclusive value=\"120\"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

So I want it to get converted to Java code like this:

public void setAge(int age){
    if(age < 0 || age > 120){
         //throw some exception
    }
     //setting the age as it is a valid value
}

Is it possible in JAXB?

Had seen some WebService Client stub generator doing this maybe axis2 webservice but not sure.


回答1:


The JAXB (JSR-222) specification does not cover generating fail fast logic into the domain model. A common practice now is to express validation rules in the form of annotations (or XML) and run validation on them. Bean Validation (JSR-303) standardizes this and is available in any Java EE 6 implementation.

XJC Extensions

I have not tried the following extension myself but it appears as though it will generate Bean Validation (JSR-303) annotations onto the domain model representation validation rules from the XML schema. As XJC is very extensible there may be other plug-ins available as well.

  • http://code.google.com/p/krasa-jaxb-tools/



回答2:


The suggested way to perform this validation in JAXB is switching on schema validation on the marshaller resp. unmarshaller:

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
Schema schema = schemaFactory.newSchema(...);

ValidationEventHandler valHandler = new ValidationEventHandler() {
  public boolean handleEvent(ValidationEvent event) {
      ...
  }
};

marshaller.setSchema(schema);
marshaller.setEventHandler(valHandler);



回答3:


You can try JAXB-Facets. Quick snippet:

class MyClass {

    @MinOccurs(1) @MaxOccurs(10)
    @Facets(minInclusive=-100, maxInclusive=100)
    public List<Integer> value;

    @Facets(pattern="[a-z][a-z0-9]{0,4}")
    public String name;

}


来源:https://stackoverflow.com/questions/13775465/does-jaxb-support-xsdrestriction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!