How to validate an XML against schema using JAXB?

笑着哭i 提交于 2019-12-18 12:19:13

问题


I am working with XML and JAXB as I am unmarshalling and marshalling the XML into Java objects and vice versa. Now I am trying to validate our XML against our schema(test.xsd). Suppose if any required field is missing in my XML, then I would like to know which field is missing after validating the XML against schema test.xsd.

public void unmarshal(final InputStream is) {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    final XMLStreamReader reader = factory.createXMLStreamReader(is);

    Object req = unmarshaller.unmarshal(reader);

    // how would I validate here?
}

How would I validate my XML against test.xsd schema. My test.xsd schema path is -

C:\workspace\one\two\three\src\main\java\com\package\serv\ap\versionOne\test.xsd

UPDATE: loading test.xsd as:

Schema schema = factorySchema.newSchema(new File("C:\\workspace\\one\\two\\three\\src\\main\\java\\com\\package\\serv\\ap\\versionOne\\test.xsd"));

回答1:


You just need to set an instance of javax.xml.validation.Schema on the Unmarshaller before you do the unmarshal. You can specify an implementation of ValidationEventHandler on the Unmarshaller to catch any problems that occur during the unmarshal process.

  • http://docs.oracle.com/javase/7/docs/api/javax/xml/bind/Unmarshaller.html#setSchema%28javax.xml.validation.Schema%29

For More Information

I have written more about this use case on my blog:

  • http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html


来源:https://stackoverflow.com/questions/24760796/how-to-validate-an-xml-against-schema-using-jaxb

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