Does JAXB support xsd:restriction?

前端 未结 3 941
我在风中等你
我在风中等你 2020-11-28 09:11

  
    
      
      

        
相关标签:
3条回答
  • 2020-11-28 09:54

    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.

    • https://github.com/krasa/krasa-jaxb-tools
    0 讨论(0)
  • 2020-11-28 09:56

    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;
    
    }
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题