fre*_*iew 10 java xml validation
我有两个xsd文件来验证xml.但问题是我的代码只需要一个xsd.如何在以下代码中使用其他xsd?我不知道我应该在哪里放置/调用第二个xsd文件.
private void validate(File xmlF,File xsd1,File xsd2) {
try {
url = new URL(xsd.toURI().toString());// xsd1
} catch (MalformedURLException e) {
e.printStackTrace();
}
source = new StreamSource(xml); // xml
try {
System.out.println(url);
schema = schemaFactory.newSchema(url);
} catch (SAXException e) {
e.printStackTrace();
}
validator = schema.newValidator();
System.out.println(xml);
try {
validator.validate(source);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
Wiv*_*ani 25
在SO或Google上搜索时有大量点击.其中一个是这个问题,作者找到了自己的解决方案,并报告以下代码将多个xsd添加到验证器:
Schema schema = factory().newSchema(new Source[] {
new StreamSource(stream("foo.xsd")),
new StreamSource(stream("Alpha.xsd")),
new StreamSource(stream("Mercury.xsd")),
});
Run Code Online (Sandbox Code Playgroud)
但是,直接使用InputStream
on时StreamSource
,解析程序无法加载任何引用的XSD文件.例如,如果文件xsd1
导入或包含第三个文件(不是xsd2
),则架构创建将失败.您应该设置系统标识符(setSystemId
)或(甚至更好)使用StreamSource(File f)
构造函数.
调整为您的示例代码:
try {
schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schema = schemaFactory.newSchema(new Source[] {
new StreamSource(xsd1), new StreamSource(xsd2)
});
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
注意:
如果使用类路径资源,我更喜欢StreamSource(String systemId)
构造函数(而不是创建一个File
):
new StreamSource(getClass().getClassLoader().getResource("a.xsd").toExternalForm());
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15306 次 |
最近记录: |