如何在使用sax解析器解析给定xsd文件时验证xml文件?

tan*_*ens 6 java xml xsd

我想使用SAXParser或XMLReader解析xml文件,并验证该文件是否符合特定的xsd 文件(new File( "example.xsd" )).

这很容易

  1. 使用此SO答案中Validator类似步骤,在额外步骤中对xsd文件进行验证.

  2. 通过"http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation"此SO答案中指定xsd的名称来解析时进行验证.

但是我如何验证一段new File( "example.xsd" ) 时间的解析

McD*_*ell 5

假设 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;
  }
});
Run Code Online (Sandbox Code Playgroud)

您可以通过覆盖处理程序上的错误方法并按照您认为合适的方式操作来处理验证错误。