Can one validate marshalled XML with JAXB 2.0?

放肆的年华 提交于 2020-01-20 16:57:31

问题


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.

Many thanks.


回答1:


Validation capabilities have been expanded in JAXB 2.0 through the use of the JAXP 1.3 Schema Validation Framework.

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.

Please check this reference.




回答2:


If you are looking to verify the Java objects generate valid XML according to a schema, look at the JAXB-Verification project:

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.



来源:https://stackoverflow.com/questions/805989/can-one-validate-marshalled-xml-with-jaxb-2-0

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