Java 可以使用 JAXB 2.0 验证编组的 XML 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/805989/
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
Can one validate marshalled XML with JAXB 2.0?
提问by Vidar
Apparently in version 2 of JAXB - the validator class has been deprecated - does this mean the marshaller is automatically validating your XML? If so it doesn't seem to be complaining about some of the incorrect XML I am forming! Can anyone give me some advice on how I can validate marshalled XML to make sure it conforms to the XSD schema.
显然在 JAXB 的第 2 版中 - 验证器类已被弃用 - 这是否意味着编组器正在自动验证您的 XML?如果是这样,它似乎不会抱怨我正在形成的一些不正确的 XML!谁能给我一些关于如何验证编组 XML 以确保它符合 XSD 模式的建议。
Many thanks.
非常感谢。
采纳答案by bruno conde
Validation capabilities have been expanded in JAXB 2.0 through the use of the JAXP 1.3 Schema Validation Framework.
通过使用 JAXP 1.3 Schema Validation Framework,JAXB 2.0 中的验证功能得到了扩展。
Where before you did:
你之前在哪里:
unmarshaller.setValidating(true);
now you need to do:
现在你需要做:
SchemaFactory sf = SchemaFactory.newInstance(
javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("myschema.xsd"));
unmarshaller.setSchema(schema);
If you pass null into setSchema
, it disables validation.
如果您将 null 传递给setSchema
,则会禁用验证。
Please check this reference.
请检查此参考。
回答by Eric Bronnimann
If you are looking to verify the Java objects generate valid XML according to a schema, look at the JAXB-Verification project:
如果您希望根据模式验证 Java 对象生成有效的 XML,请查看 JAXB-Verification 项目:
https://jaxb-verification.dev.java.net/
https://jaxb-verification.dev.java.net/
It is a JAXB RI plugin to xjc that will generate an ObjectVerifier implementation for the XML schema. This avoids having to marshal the Java objects in order to validate the XML.
它是 xjc 的 JAXB RI 插件,将为 XML 模式生成 ObjectVerifier 实现。这避免了必须编组 Java 对象以验证 XML。