使用 DynamicJAXBContext 进行验证

Validation with DynamicJAXBContext

如何在解组期间打开验证? [moxy 2.6.0]

第一个有趣的事情是我需要放置应该已经在 DynamicContext 中的架构。但即使再次将架构设置为 unmarshaller,它也会给我一个错误。

我试过用这个:

 final JAXBUnmarshaller unmarshaller = dynamicJAXBContext.createUnmarshaller();
        //unmarshaller.setSchema();
        final Schema schema = schemas.get(type);
        unmarshaller.setSchema(schema);
        unmarshaller.setValidating(true);

它给出了一个例外。看起来破坏的部分是从 DynamicContext

放在那里的一些元素
Exception Description: An error occurred resolving the XML Schema.
Internal Exception: java.lang.NullPointerException
Exception [EclipseLink-25012] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: An error occurred resolving the XML Schema.
Internal Exception: java.lang.NullPointerException
    at org.eclipse.persistence.exceptions.XMLMarshalException.errorResolvingXMLSchema(XMLMarshalException.java:186)
    at org.eclipse.persistence.oxm.schema.XMLSchemaClassPathReference.getURL(XMLSchemaClassPathReference.java:48)
    at org.eclipse.persistence.oxm.XMLUnmarshaller.initializeSchemas(XMLUnmarshaller.java:211)
    at org.eclipse.persistence.oxm.XMLUnmarshaller.setValidationMode(XMLUnmarshaller.java:155)
    at org.eclipse.persistence.jaxb.JAXBUnmarshaller.setValidating(JAXBUnmarshaller.java:756)

这里的问题是找不到架构。您设置了 null 而不是 Schema 实例。

顺便说一句。方法

javax.xml.bind.Unmarshaller#setValidating

自 JAXB 2.0 起已弃用。使用方法

javax.xml.bind.Unmarshaller#setSchema

会完成这项工作。