java JAXB 是否支持 xsd:restriction?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13775465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does JAXB support xsd:restriction?
提问by Narendra Pathai
<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:
所以我希望它像这样被转换成 Java 代码:
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?
在 JAXB 中可能吗?
Had seen some WebService Client stub generator doing this maybe axis2 webservice but not sure.
已经看到一些 WebService 客户端存根生成器这样做可能是axis2 webservice 但不确定。
采纳答案by bdoughan
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.
的JAXB(JSR-222)规范没有盖产生快速失败逻辑到域模型。现在的一种常见做法是以注释(或 XML)的形式表达验证规则并对其运行验证。 Bean Validation (JSR-303)对此进行了标准化,可用于任何 Java EE 6 实现。
XJC Extensions
XJC 扩展
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.
我自己没有尝试过以下扩展,但它似乎会在来自 XML 模式的域模型表示验证规则上生成Bean 验证 (JSR-303)注释。由于 XJC 具有很强的可扩展性,因此可能还有其他可用的插件。
回答by vbence
You can try JAXB-Facets. Quick snippet:
你可以试试JAXB-Facets。快速片段:
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;
}
回答by Drunix
The suggested way to perform this validation in JAXB is switching on schema validation on the marshaller resp. unmarshaller:
在 JAXB 中执行此验证的建议方法是在编组器响应上打开模式验证。解组器:
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);