【问题标题】:How to validate a xml file against a given xsd file while parsing it with a sax parser?如何在使用 sax 解析器解析时针对给定的 xsd 文件验证 xml 文件?
【发布时间】:2009-10-27 11:54:22
【问题描述】:

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

很容易

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

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

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

【问题讨论】:

    标签: java xml xsd


    【解决方案1】:

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

    【讨论】:

    • 解析器似乎仍然使用xml文件中定义的模式,而不是我用schemaFactory( newSchema(...))设置的模式。
    • 这不是我看到的行为(解析器总是根据工厂设置的模式进行验证,即使在文档中设置了模式)。没有示例文档/代码,很难识别问题。
    猜你喜欢
    • 2013-08-30
    • 1970-01-01
    • 2015-06-28
    • 2017-07-27
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    相关资源
    最近更新 更多