我想使用SAXParser或XMLReader解析xml文件,并验证该文件是否符合特定的xsd 文件(new File( "example.xsd" )
)。
很容易
使用this SO answer中的Validator
在额外步骤中对xsd文件进行验证。
通过在this SO answer中指定xsd的名称"http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation"
来解析时进行验证。
但如何在解析时验证new File( "example.xsd" )
?
答案 0 :(得分:3)
假设Java 5或更高版本,请在SAXParserFactory上设置架构:
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File("myschema.xsd"));
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
saxFactory.setSchema(schema);
SAXParser parser = saxFactory.newSAXParser();
parser.parse("data.xml", new DefaultHandler() {
// TODO: other handler methods
@Override
public void error(SAXParseException e) throws SAXException {
throw e;
}
});
您可以通过覆盖处理程序上的error method并按您认为合适的方式处理验证错误。