`
qqdwll
  • 浏览: 131620 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

[转载] http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html

    博客分类:
  • Java
阅读更多
原文 http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html

Validation is a powerful tool. It enables you to quickly check that input is roughly in the form you expect and quickly reject any document that is too far away from what your process can handle. If there's a problem with the data, it's better to find out earlier than later.

In the context of Extensible Markup Language (XML), validation normally involves writing a detailed specification for the document's contents in any of several schema languages such as the World Wide Web Consortium (W3C) XML Schema Language (XSD), RELAX NG, Document Type Definitions (DTDs), and Schematron. Sometimes validation is performed while parsing, sometimes immediately after. However, it's usually done before any further processing of the input takes place. (This description is painted with broad strokes -- there are exceptions.)

Until recently, the exact Application Programming Interface (API) by which programs requested validation varied with the schema language and parser. DTDs and XSD were normally accessed as configuration options in Simple API for XML (SAX), Document Object Model (DOM), and Java™ API for XML Processing (JAXP). RELAX NG required a custom library and API. Schematron might use the Transformations API for XML(TrAX); and still other schema languages required programmers to learn still more APIs, even though they were performing essentially the same operation.

Java 5 introduced the javax.xml.validation package to provide a schema-language-independent interface to validation services. This package is also available in Java 1.3 and later when you install JAXP 1.3 separately. Among other products, an implementation of this library is included with Xerces 2.8.

Validation

The javax.xml.validation API uses three classes to validate documents: SchemaFactory, Schema, and Validator. It also makes extensive use of the javax.xml.transform.Source interface from TrAX to represent the XML documents. In brief, a SchemaFactory reads the schema document (often an XML file) from which it creates a Schema object. The Schema object creates a Validator object. Finally, the Validator object validates an XML document represented as a Source.

Listing 1 shows a simple program to validate a URL entered on the command line against the DocBook XSD schema.


Listing 1. Validating an Extensible Hypertext Markup Language (XHTML) document
import java.io.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.xml.sax.SAXException;

public class DocbookXSDCheck {

    public static void main(String[] args) throws SAXException, IOException {

        // 1. Lookup a factory for the W3C XML Schema language
        SchemaFactory factory =
            SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
       
        // 2. Compile the schema.
        // Here the schema is loaded from a java.io.File, but you could use
        // a java.net.URL or a javax.xml.transform.Source instead.
        File schemaLocation = new File("/opt/xml/docbook/xsd/docbook.xsd");
        Schema schema = factory.newSchema(schemaLocation);
   
        // 3. Get a validator from the schema.
        Validator validator = schema.newValidator();
       
        // 4. Parse the document you want to check.
        Source source = new StreamSource(args[0]);
       
        // 5. Check the document
        try {
            validator.validate(source);
            System.out.println(args[0] + " is valid.");
        }
        catch (SAXException ex) {
            System.out.println(args[0] + " is not valid because ");
            System.out.println(ex.getMessage());
        } 
       
    }

}


Here's some typical output when checking an invalid document using the version of Xerces bundled with Java 2 Software Development Kit (JDK) 5.0:

file:///Users/elharo/CS905/Course_Notes.xml is not valid because cvc-complex-type.2.3: Element 'legalnotice' cannot have character [children], because the type's content type is element-only.

You can easily change the schema to validate against, the document to validate, and even the schema language. However, in all cases, validation follows these five steps:

Load a schema factory for the language the schema is written in.
Compile the schema from its source.
Create a validator from the compiled schema.
Create a Source object for the document you want to validate. A StreamSource is usually simplest.
Validate the input source. If the document is invalid, the validate() method throws a SAXException. Otherwise, it returns quietly.
You can reuse the same validator and the same schema multiple times in series. However, only the schema is thread safe. Validators and schema factories are not. If you validate in multiple threads simultaneously, make sure each one has its own Validator and SchemaFactory objects.

Validate against a document-specified schema

Some documents specify the schema they expect to be validated against, typically using xsi:noNamespaceSchemaLocation and/or xsi:schemaLocation attributes like this:

<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="http://www.example.com/document.xsd">
  ...


If you create a schema without specifying a URL, file, or source, then the Java language creates one that looks in the document being validated to find the schema it should use. For example:

SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = factory.newSchema();



However, normally this isn't what you want. Usually the document consumer should choose the schema, not the document producer. Furthermore, this approach works only for XSD. All other schema languages require an explicitly specified schema location.


--------------------------------------------------------------------------------
Abstract factories

SchemaFactory is an abstract factory. The abstract factory design pattern enables this one API to support many different schema languages and object models. A single implementation usually supports only a subset of the numerous languages and models. However, once you learn the API for validating DOM documents against RELAX NG schemas (for instance), you can use the same API to validate JDOM documents against W3C schemas.

For example, Listing 2 shows a program that validates DocBook documents against DocBook's RELAX NG schema. It's almost identical to Listing 1. The only things that have changed are the location of the schema and the URL that identifies the schema language.


Listing 2. Validating a DocBook document using RELAX NG
import java.io.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import org.xml.sax.SAXException;

public class DocbookRELAXNGCheck {

    public static void main(String[] args) throws SAXException, IOException {

        // 1. Specify you want a factory for RELAX NG
        SchemaFactory factory
         = SchemaFactory.newInstance("http://relaxng.org/ns/structure/1.0");
       
        // 2. Load the specific schema you want.
        // Here I load it from a java.io.File, but we could also use a
        // java.net.URL or a javax.xml.transform.Source
        File schemaLocation = new File("/opt/xml/docbook/rng/docbook.rng");
       
        // 3. Compile the schema.
        Schema schema = factory.newSchema(schemaLocation);
   
        // 4. Get a validator from the schema.
        Validator validator = schema.newValidator();
       
        // 5. Parse the document you want to check.
        String input
         = "file:///Users/elharo/Projects/workspace/CS905/build/Java_Course_Notes.xml";
       
        // 6. Check the document
        try {
            validator.validate(source);
            System.out.println(input + " is valid.");
        }
        catch (SAXException ex) {
            System.out.println(input + " is not valid because ");
            System.out.println(ex.getMessage());
        } 
       
    }

}


If you run this program with the stock Sun JDK and no extra libraries, you'll probably see something like this:

Exception in thread "main" java.lang.IllegalArgumentException:
http://relaxng.org/ns/structure/1.0
at javax.xml.validation.SchemaFactory.newInstance(SchemaFactory.java:186)
at DocbookRELAXNGCheck.main(DocbookRELAXNGCheck.java:14)


This is because, out of the box, the JDK doesn't include a RELAX NG validator. When the schema language isn't recognized, SchemaFactory.newInstance() throws an IllegalArgumentException. However, if you install a RELAX NG library such as Jing and a JAXP 1.3 adapter, then it should produce the same answer the W3C schema does.

Identify the schema language

The javax.xml.constants class defines several constants to identify schema languages:

XMLConstants.W3C_XML_SCHEMA_NS_URI: http://www.w3.org/2001/XMLSchema
XMLConstants.RELAXNG_NS_URI: http://relaxng.org/ns/structure/1.0
XMLConstants.XML_DTD_NS_URI: http://www.w3.org/TR/REC-xml
This isn't a closed list. Implementations are free to add other URLs to this list to identify other schema languages. Typically, the URL is the namespace Uniform Resource Identifier (URI) for the schema language. For example, the URL http://www.ascc.net/xml/schematron identifies Schematron schemas.

Sun's JDK 5 only supports XSD schemas. Although DTD validation is supported, it isn't accessible through the javax.xml.validation API. For DTDs, you have to use the regular SAX XMLReader class. However, you can install additional libraries that add support for these and other schema languages.

How schema factories are located

The Java programming language isn't limited to a single schema factory. When you pass a URI identifying a particular schema language to SchemaFactory.newInstance(), it searches the following locations in this order to find a matching factory:

The class named by the "javax.xml.validation.SchemaFactory:schemaURL" system property
The class named by the "javax.xml.validation.SchemaFactory:schemaURL" property found in the $java.home/lib/jaxp.properties file
javax.xml.validation.SchemaFactory service providers found in the META-INF/services directories of any available Java Archive (JAR) files
A platform default SchemaFactory, com.sun.org.apache.xerces.internal.jaxp.validation.xs.SchemaFactoryImpl in JDK 5
To add support for your own custom schema language and corresponding validator, all you have to do is write subclasses of SchemaFactory, Schema, and Validator that know how to process your schema language. Then, install your JAR in one of these four locations. This is useful for adding constraints that are more easily checked in a Turing-complete language like Java than in a declarative language like the W3C XML Schema language. You can define a mini-schema language, write a quick implementation, and plug it into the validation layer.


--------------------------------------------------------------------------------

Error handlers

The default response from a schema is to throw a SAXException if there's a problem and do nothing if there isn't. However, you can provide a SAX ErrorHandler to receive more detailed information about the document's problems. For example, suppose you want to log all validation errors, but you don't want to stop processing when you encounter one. You can install an error handler such as that in Listing 3.


Listing 3. An error handler that merely logs non-fatal validity errors
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ForgivingErrorHandler implements ErrorHandler {

    public void warning(SAXParseException ex) {
        System.err.println(ex.getMessage());
    }

    public void error(SAXParseException ex) {
        System.err.println(ex.getMessage());
    }

    public void fatalError(SAXParseException ex) throws SAXException {
        throw ex;
    }

}


To install this error handler, you create an instance of it and pass that instance to the Validator's setErrorHandler() method:

  ErrorHandler lenient = new ForgivingErrorHandler();
  validator.setErrorHandler(lenient);


--------------------------------------------------------------------------------

Schema augmentation

Some schemas do more than validate. As well as providing a true-false answer to the question of whether a document is valid, they also augment the document with additional information. For example, they can provide default attribute values. They might also assign types like int or gYear to an element or attribute. The validator can create such type-augmented documents and write them onto a javax.xml.transform.Result object. All you need to do is pass a Result as the second argument to validate. For example, Listing 4 both validates an input document and creates an augmented DOM document from the combination of the input with the schema.


Listing 4. Augmenting a document with a schema
import java.io.*;
import javax.xml.transform.dom.*;
import javax.xml.validation.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

public class DocbookXSDAugmenter {

    public static void main(String[] args)
      throws SAXException, IOException, ParserConfigurationException {

        SchemaFactory factory
         = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        File schemaLocation = new File("/opt/xml/docbook/xsd/docbook.xsd");
        Schema schema = factory.newSchema(schemaLocation);
        Validator validator = schema.newValidator();
       
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(new File(args[0]));
       
        DOMSource source = new DOMSource(doc);
        DOMResult result = new DOMResult();
       
        try {
            validator.validate(source, result);
            Document augmented = (Document) result.getNode();
            // do whatever you need to do with the augmented document...
        }
        catch (SAXException ex) {
            System.out.println(args[0] + " is not valid because ");
            System.out.println(ex.getMessage());
        } 
       
    }

}


This procedure can't transform an arbitrary source into an arbitrary result. It doesn't work at all for stream sources and results. SAX sources can be augmented into SAX results, and DOM sources into DOM results; but SAX sources can't be augmented to DOM results or vice versa. If you need to do that, first augment into the matching result -- SAX for SAX and DOM for DOM -- and then use TrAX's identity transform to change the model.

This technique isn't recommended, though. Putting all the information the document requires in the instance is far more reliable than splitting it between the instance and the schema. You might validate, but not everyone will.


--------------------------------------------------------------------------------

Type information

The W3C XML Schema Language is heavily based on the notion of types. Elements and attributes are declared to be of type int, double, date, duration, person, PhoneNumber, or anything else you can imagine. The Java Validation API includes a means to report such types, although it's surprisingly independent of the rest of the package.

Types are identified by an org.w3c.dom.TypeInfo object. This simple interface, summarized in Listing 5, tells you the local name and namespace URI of a type. You can also tell whether and how a type is derived from another type. Beyond that, understanding the type is up to your program. The Java language doesn't tell you what it means or convert the data to a Java type such as double or java.util.Date.


Listing 5. The DOM TypeInfo interface
package org.w3c.dom;

public interface TypeInfo {

  public static final int DERIVATION_RESTRICTION;
  public static final int DERIVATION_EXTENSION;
  public static final int DERIVATION_UNION;

  public String  getTypeName();
  public String  getTypeNamespace()
  public boolean isDerivedFrom(String namespace, String name, int derivationMethod);

}


To get TypeInfo objects, you ask the Schema object for a ValidatorHandler rather than a Validator. ValidatorHandler implements SAX's ContentHandler interface. Then, you install this handler in a SAX parser.

You also install your own ContentHandler in the ValidatorHandler (not the parser); the ValidatorHandler will forward the augmented events on to your ContentHandler.

The ValidatorHandler makes available a TypeInfoProvider that your ContentHandler can call at any time to find out the type of the current element or one of its attributes. It can also tell you whether an attribute is an ID, and whether the attribute was explicitly specified in the document or defaulted in from the schema. Listing 6 summarizes this class.


Listing 6. The TypeInfoProvider class
package javax.xml.validation;

public abstract class TypeInfoProvider {

  public abstract TypeInfo getElementTypeInfo();
  public abstract TypeInfo getAttributeTypeInfo(int index);
  public abstract boolean  isIdAttribute(int index);
  public abstract boolean  isSpecified(int index);

}


Finally, you parse the document with the SAX XMLReader. Listing 7 shows a simple program that uses all these classes and interfaces to print out the names of all the types of the elements in a document.


Listing 7. Listing element types
import java.io.*;
import javax.xml.validation.*;

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class TypeLister extends DefaultHandler {

    private TypeInfoProvider provider;
   
    public TypeLister(TypeInfoProvider provider) {
        this.provider = provider;
    }

    public static void main(String[] args) throws SAXException, IOException {

        SchemaFactory factory
         = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        File schemaLocation = new File("/opt/xml/docbook/xsd/docbook.xsd");
        Schema schema = factory.newSchema(schemaLocation);
   
        ValidatorHandler vHandler = schema.newValidatorHandler();
        TypeInfoProvider provider = vHandler.getTypeInfoProvider();
        ContentHandler   cHandler = new TypeLister(provider);
        vHandler.setContentHandler(cHandler);
       
        XMLReader parser = XMLReaderFactory.createXMLReader();
        parser.setContentHandler(vHandler);
        parser.parse(args[0]);
       
    }
   
    public void startElement(String namespace, String localName,
      String qualifiedName, Attributes atts) throws SAXException {
        String type = provider.getElementTypeInfo().getTypeName();
        System.out.println(qualifiedName + ": " + type);
    }

}


Here's the start of the output from running this code on a typical DocBook document:

book: #AnonType_book
title: #AnonType_title
subtitle: #AnonType_subtitle
info: #AnonType_info
copyright: #AnonType_copyright
year: #AnonType_year
holder: #AnonType_holder
author: #AnonType_author
personname: #AnonType_personname
firstname: #AnonType_firstname
othername: #AnonType_othername
surname: #AnonType_surname
personblurb: #AnonType_personblurb
para: #AnonType_para
link: #AnonType_link


As you can see, the DocBook schema assigns most elements anonymous complex types. Obviously, this will vary from one schema to the next.


--------------------------------------------------------------------------------
Conclusion

The world would be a poorer place if everyone spoke just one language. Programmers would be unhappy if they had only one programming language to choose from. Different languages suit different tasks better, and some tasks require more than one language. XML schemas are no different. You can choose from a plethora of useful schema languages. In Java 5 with javax.xml.validation, you have an API that can handle all of them.
分享到:
评论

相关推荐

    http://www.ibm.com/developerworks/cn/linux/l-cn-mthreadps/

    NULL 博文链接:https://jacky-dai.iteye.com/blog/2311509

    setuptools_0

    4、可爱的 Python: 使用 setuptools 孵化 Python egg:http://www.ibm.com/developerworks/cn/linux/l-cppeak3.html 5 5、Python中setuptools的简介:http://www.juziblog.com/?p=365001 6 6、ez_setup.py脚本:...

    websphere commerce的使用即websphere commerce图解.pdf

    websphere commerce的使用即websphere commerce图解.在网上扒了半天才找到的稀品啊!IBM创建商品店铺...http://www.ibm.com/developerworks/cn/websphere/library/techarticles/0503_mistry/0503_mistry.html

    XMLHttpRequest手册

    http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro1.html 掌握 Ajax,第 2 部分: 使用 JavaScript 和 Ajax 发出异步请求 http://www.ibm.com/developerworks/cn/xml/wa-ajaxintro2/ 掌握 Ajax,第 3 部分: ...

    Spring入门笔记.md

    [架构图](http://www.ibm.com/developerworks/cn/java/j-lo-spring-principle/image001.gif) 然后我们皆可以写我们的demo了 ### 我们的Bean类 对于bean的理解,希望大家是把他看成Object对象,他可以是任何对象,...

    webharvest 中文翻译文档

    1. webharvest官方网站...http://www.ibm.com/developerworks/cn/xml/x-xqueryl/ 可以在XML相关书籍中找到实例。 文档及相关资料就免费提供给大家了,另外我将自己抓取新浪网的实例也上传了与大家共享,欢迎一块下载!

    Java学习从入门到精通[原创]

    2、http://www-900.ibm.com/developerWorks/cn/ IBM的developerWorks网站,英语好的直接去英文主站点看。这里不但是一个极好的面向对象的分析设计网站,也是WebServices,Java,Linux极好的网站。强烈推荐!!! 3、...

    coLinux 0.7.9 DEVTMPFS

    Tips-02: http://www.ibm.com/developerworks/cn/linux/l-virtualization-colinux/ Tips-03: coLinux-0.7.9-src.tar.gz, /doc/building [Develop Env] Gentoo Linux i686 2011-10-25 stage3-i686-20111025.tar....

    如何才算掌握Java(J2EE篇)

    时常看到一些人说掌握了Java,但是让他们用Java做一个实际的项目可能又困难重重,在这里...

    使用Android和XML构建动态用户界面

    有几个网站从事一些非盈利服务,提供一些可轻松设置和使用的表单来进行民意测验和数据收集。本教程介绍一个简单的架构来为 Android ... http://www.ibm.com/developerworks/cn/xml/tutorials/x-andddyntut/index.html

    gradle-1.7-all

    http://www.ibm.com/developerworks/cn/opensource/os-cn-gradle/index.html Ant,Maven,Gradle 简单比较 Ant 是我们过去构建系统基本都会用到的,xml 脚本文件中包括若干 task 任务,任务之间可以互相依赖,对于一...

    基于事件的NIO多线程服务器打包

    原帖来自:http://www.ibm.com/developerworks/cn/java/l-niosvr/#author 进行了打包,并生成javadoc,方便使用. 该包封装过的NIO比sun本身的更容易处理 server中只有区区几行就搞定了: //创建listener TimeHandler ...

    maven2经典(新手必备).doc

    http://www-128.ibm.com/developerworks/cn/opensource/os-maven2/index.html 二、maven2安装 1、首先去官方网站下载之:http://maven.apache.org/download.html,我选择的是截至目前最新版本maven2.0.4版本 2、...

    PowerVM 共享存储池-图解.docx

    PowerVM共享存储池(ShareStoragePool)的功能与实现HYPERLINK"http://www.ibm.com/developerworks/cn/aix/library/1112_huyf_sharestoragepool/index.html?ca=dat"\l"author1"胡云飞,资深IT专家,IBM简介: 本文...

    carregadorRecursos:资源加载器(图像、音频、json),用于需要控制所用资源加载的应用程序,例如控制游戏资源

    加载器资源 资源加载器(图像、音频、json),用于需要控制所用资源加载的应用程序,例如控制游戏资源 使用示例: ... "http://www.ibm.com/developerworks/java/library/j-html5-game6/runner-tracks.jpg",

    elasticsearch java客户端Jest入门实例

    本实例参考网上代码:http://www.ibm.com/developerworks/cn/java/j-javadev2-24/ 通过Jest和Junit单元测试的方法创建索引和检索 第一步:启动一个elasticsearch服务,bin目录下的elasticsearch.bat 第二步:建索引,...

    在 Windows 中实现 Java 本地方法

    转自:http://www.ibm.com/developerworks/cn/java/jnimthds/ PDF链接:http://pan.baidu.c

    IBM Rational Application Developer 7.5永久使用许可证即安装说明

    IBM Rational Application Developer 7.5安装完后,...//www.ibm.com/developerworks/cn/rational/r-gaowb/#N100C8,好好看看就明白了,研究了半天才搞懂怎么用这个nodelock文件,这个本来有人已经传了,不过没有写使用说明.

    Eclipse插件开发Eclipse插件开发

    Eclipse插件开发Eclipse插件开发Eclipse插件开发Eclipse插件开发http://www.ibm.com/developerworks/cn/java/os-ecplug/

    wxPython-入门教程.pdf

    wxWindows 介绍请参阅 developerWorks上 "细述 wxWindows" )wxWindows 库 是为了最大可移植性 C/C 库而抽取 GUI 功能所以 wxWindows 应用和生俱来地可以运行在 Windows、带 X、 KDE 或 Gnome UNIX 或者 wxWindows 已...

Global site tag (gtag.js) - Google Analytics