如何使用JAXB根据模式验证XML ?

时间:2022-02-28 21:50:16

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.

我正在处理XML和JAXB,因为我正在分解XML并将其编组到Java对象中,反之亦然。现在,我正在尝试根据模式(test.xsd)验证XML。假设在我的XML中缺少任何必需的字段,那么我想知道在根据schema test.xsd验证XML之后丢失了哪个字段。

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 -

如何对XML进行测试验证。xsd模式。我的测试。xsd模式路径是-

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

C:\ workspace \ \ 2 \ 3 \ src \主要包\ java \ com \ \ \服务美联社versionOne \ \ test.xsd

UPDATE: loading test.xsd as:

更新:加载测试。xsd:

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

1 个解决方案

#1


18  

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.

您只需要设置一个javax.xml.validation的实例。在你做unmarshal之前,在Unmarshaller上的模式。您可以在Unmarshaller上指定ValidationEventHandler的实现,以捕获在unmarshal过程中发生的任何问题。

For More Information

的更多信息

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

我在我的博客上写了更多关于这个用例的文章:

#1


18  

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.

您只需要设置一个javax.xml.validation的实例。在你做unmarshal之前,在Unmarshaller上的模式。您可以在Unmarshaller上指定ValidationEventHandler的实现,以捕获在unmarshal过程中发生的任何问题。

For More Information

的更多信息

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

我在我的博客上写了更多关于这个用例的文章: