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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1630319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:21:02  来源:igfitidea点击:

How to validate a xml file against a given xsd file while parsing it with a sax parser?

javaxmlxsd

提问by tangens

I want to parse a xml file using a SAXParser or XMLReader and verify that the file conforms to a specific xsd file(new File( "example.xsd" )).

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

It's easy to

很容易

  1. do the validation against a xsd file in an extra step using a Validatorlike in this SO answer.

  2. to validate while parsing by specifying the name of the xsd as "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation"like in this SO answer.

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

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

But how can I validate against a new File( "example.xsd" )while parsing?

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

回答by McDowell

Assuming Java 5 or above, set the schema on the SAXParserFactory:

假设 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;
  }
});

You handle validation errors by overriding the error methodon your handler and acting as you see fit.

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