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

时间:2009-10-27 11:54:23

标签: java xml xsd

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

很容易

  1. 使用this SO answer中的Validator在额外步骤中对xsd文件进行验证。

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

  3. 但如何在解析时验证new File( "example.xsd" )

1 个答案:

答案 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并按您认为合适的方式处理验证错误。