【发布时间】:2014-01-02 13:06:27
【问题描述】:
我有这样的方法:
private static <T> T readXML(final String file, final String schemaFile, final Class<T> clazz) {
try {
final JAXBContext context = JAXBContext.newInstance(clazz);
final Unmarshaller unmarshaller = context.createUnmarshaller();
unmarshaller.setEventHandler(new EventHandler());
final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final String directory = System.getProperty("schema.dir");
unmarshaller.setSchema(schemaFactory.newSchema(new File(directory, schemaFile)));
return clazz.cast(unmarshaller.unmarshal(new File(directory, file)));
} catch (final Exception ex) {
ex.printStackTrace();
}
System.exit(1);
return null;
}
我是这样使用它的:
private static final Primitives primitives = readXML("primitives.xml", "primitives.xsd", Primitives.class);
我的问题是是否可以向解组器添加自定义验证器? 我的意思是,假设我有一个名为 Foo 的 complexType。我想对其进行一些无法在 xsd 文件中描述的验证,所以我想做这样的事情:
unmarshaller.setCustomValidator(Foo.class, new MyCustomValidator());
所以每次 JAXB 读取 Foo 时都会调用 MyCustomValidator。 或者如果我不能在 xsd 文件中描述一些验证,那么我必须在 JAXB 读取完成后验证解析的类?
哦,顺便说一句...我用 xjc 从 xsd 生成了 JAXB 类。
【问题讨论】:
-
我说我想要一个自定义验证器。 schema.newValidator() 针对 xsd 进行验证。除了在 xsd 中定义之外,我还想做一些其他的验证。
标签: java xml validation jaxb xsd