Skip navigation links
Java™ Platform
Standard Ed. 8

Package javax.xml.validation

此软件包提供了一个用于验证XML文档的API。

See: 描述

Package javax.xml.validation Description

此软件包提供了一个用于验证XML文档的API。 验证是验证XML文档是指定的XML 模式的实例的过程。 XML模式定义其实例文档将表示的内容模型(也称为语法词汇 )。

有许多流行的技术可用于创建XML模式。 一些最受欢迎的包括:

以前版本的JAXP支持验证,作为XML解析器的特征,由SAXParserDocumentBuilder实例表示。

JAXP验证API将实例文档的验证与XML文档的解析分离。 这是有利于几个原因,其中一些是:

Usage example.以下示例演示如何使用Validation API验证XML文档(为了可读性,未显示某些异常处理):

  // parse an XML document into a DOM tree
    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = parser.parse(new File("instance.xml"));

    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(new File("mySchema.xsd"));
    Schema schema = factory.newSchema(schemaFile);

    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();

    // validate the DOM tree
    try {
        validator.validate(new DOMSource(document));
    } catch (SAXException e) {
        // instance document is invalid!
    } 

JAXP解析API已经与验证API集成。 应用程序可以创建具有验证 API的Schema,并使用DocumentBuilderFactory.setSchema(Schema)SAXParserFactory.setSchema(Schema)方法将其与DocumentBuilderFactorySAXParserFactory实例相关 您不应同时设置模式并在解析器工厂调用setValidating(true) 前一种技术将导致解析器使用新的验证API; 后者将使解析器使用自己的内部验证设施。 同时打开这两个选项将导致冗余行为或错误条件。

Skip navigation links
Java™ Platform
Standard Ed. 8

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2014, Oracle and/or its affiliates. All rights reserved.

本帮助文档是使用 《谷歌翻译》翻译,请与英文版配合使用