問題描述
我正在使用 XML
和 JAXB
,因為我正在將 XML 解組和編組為 Java 對象,反之亦然.現在我正在嘗試根據我們的模式(test.xsd)驗證我們的 XML.假設如果我的 XML 中缺少任何必填字段,那么我想知道在根據模式 test.xsd 驗證 XML 之后缺少哪個字段.
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?
}
我將如何根據 test.xsd 架構驗證我的 XML.我的 test.xsd 架構路徑是 -
How would I validate my XML against test.xsd schema. My test.xsd schema path is -
C:workspaceone wo hreesrcmainjavacompackageservapversionOne est.xsd
C:workspaceone wo hreesrcmainjavacompackageservapversionOne est.xsd
更新:將 test.xsd 加載為:
Schema schema = factorySchema.newSchema(new File("C:\workspace\one\two\three\src\main\java\com\package\serv\ap\versionOne\test.xsd"));
推薦答案
你只需要設置一個javax.xml.validation.Schema
在執行解組之前在 Unmarshaller
上.您可以在 Unmarshaller
上指定 ValidationEventHandler
的實現,以捕獲解組過程中發生的任何問題.
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
更多信息
我已經在我的博客上寫了更多關于這個用例的文章:
I have written more about this use case on my blog:
- http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html
這篇關于如何使用 JAXB 針對模式驗證 XML?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!