[转]Java通过XML Schema校验XML

[转]Java通过XML Schema校验XML

XML文件
<? xml version ="1.0" ?>
< note
         xmlns ="http://www.w3school.com.cn"
         xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation ="http://www.w3school.com.cn file:///D:/_dev_stu/xsdtest/src/note.xml" >

     < to >George </ to >
     < from >John </ from >
     < heading >Reminder </ heading >
     < body >Don't forget the meeting this weekend! </ body >
</ note >
 
XSD文件
<? xml version ="1.0" ?>
< xs:schema xmlns:xs ="http://www.w3.org/2001/XMLSchema"
           targetNamespace ="http://www.w3school.com.cn"
           xmlns ="http://www.w3school.com.cn"
           elementFormDefault ="qualified" >

     < xs:element name ="note" >
         < xs:complexType >
             < xs:sequence >
                 < xs:element name ="to" type ="xs:string" />
                 < xs:element name ="from" type ="xs:string" />
                 < xs:element name ="heading" type ="xs:string" />
                 < xs:element name ="body" type ="xs:string" />
             </ xs:sequence >
         </ xs:complexType >
     </ xs:element >

</ xs:schema >
 
测试代码
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXValidator;
import org.dom4j.io.XMLWriter;
import org.dom4j.util.XMLErrorHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;

/**
* Java XML校验测试
*
* @author leizhimin,2008-9-4 14:42:35
*/
public class ValidataXMLTest {
     public static void main(String[] args) {
        validateXMLByXSD();
        validateXMLByDTD();

    }

     /**
     * 通过XSD(XML Schema)校验XML
     */
     public static void validateXMLByXSD() {
        String xmlFileName = "Q:\\_dev_stu\\xsdtest\\src\\note.xml";
        String xsdFileName = "Q:\\_dev_stu\\xsdtest\\src\\note.xsd";
         try {
             //创建默认的XML错误处理器
            XMLErrorHandler errorHandler = new XMLErrorHandler();
             //获取基于 SAX 的解析器的实例
            SAXParserFactory factory = SAXParserFactory.newInstance();
             //解析器在解析时验证 XML 内容。
            factory.setValidating( true);
             //指定由此代码生成的解析器将提供对 XML 名称空间的支持。
            factory.setNamespaceAware( true);
             //使用当前配置的工厂参数创建 SAXParser 的一个新实例。
            SAXParser parser = factory.newSAXParser();
             //创建一个读取工具
            SAXReader xmlReader = new SAXReader();
             //获取要校验xml文档实例
            Document xmlDocument = (Document) xmlReader.read( new File(xmlFileName));
             //设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在 [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。
            parser.setProperty(
                     "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
            parser.setProperty(
                    "http://java.sun.com/xml/jaxp/properties/schemaSource",
                    "file:" + xsdFileName);
            //创建一个SAXValidator校验工具,并设置校验工具的属性
            SAXValidator validator = new SAXValidator(parser.getXMLReader());
            //设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。
            validator.setErrorHandler(errorHandler);
            //校验
            validator.validate(xmlDocument);

            XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
            //如果错误信息不为空,说明校验失败,打印错误信息
            if (errorHandler.getErrors().hasContent()) {
                System.out.println("XML文件通过XSD文件校验失败!");
                writer.write(errorHandler.getErrors());
            } else {
                System.out.println("Good! XML文件通过XSD文件校验成功!");
            }
        } catch (Exception ex) {
            System.out.println("XML文件: " + xmlFileName + " 通过XSD文件:" + xsdFileName + "检验失败。\n原因: " + ex.getMessage());
            ex.printStackTrace();
        }
    }

    /**
     * 通过DTD校验XML
     */
    public static void validateXMLByDTD() {
        //todo:暂时不用,以后再说吧
    }
}
 
运行结果
Good! XML文件通过XSD文件校验成功!

方法二:

最近对Schema 验证研究了一下, 代码如下:
所需JAR包需要自己下载(版本一定要正确)

public class SchemaValidation {


    public static void main(String[] args) {
        validate();
    }

    public static void validate() {
        try {
            SchemaValidation demo = new SchemaValidation();
            // Give the xml(标准化越来越近了) and schema name
            InputStream xml(标准化越来越近了)String = demo.getClass().getResourceAsStream("GBAInit.xml(标准化越来越近了)");
            InputStream schemaStr = demo.getClass().getResourceAsStream("GBAInitSchema.xsd");
   
            SAXReader reader = createSAXReader(schemaStr);
            System.out.println("XSD parse successfully !");
           
            Document document = reader.read(xml(标准化越来越近了)String);
            System.out.println("Successfully validation .. . ");
        } catch (DocumentException e) {
            System.out.println("Exception occurred: " + e);
            Throwable nestedException = e.getNestedException();
            if (nestedException != null) {
                System.out.println("NestedException: " + nestedException);
                nestedException.printStackTrace();
            } else {
                e.printStackTrace();
            }
        } catch (Throwable t) {
            System.out.println("Exception occurred: " + t);
            t.printStackTrace();
        }
    }

    /** Registers the Verifier with the SAXReader */
    protected SAXReader createSAXReader(InputStream schemaURI) throws Exception {

        System.out.println("Loaded schema document: " + schemaURI);

        // use autodetection of schemas
        VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl();
        Schema schema = factory.compileSchema(schemaURI);

        Verifier verifier = schema.newVerifier();
        verifier.setErrorHandler(new ErrorHandler() {
            public void error(SAXParseException e) {
                System.out.println("ERROR: " + e);
            }

            public void fatalError(SAXParseException e) {
                System.out.println("FATAL: " + e);
            }

            public void warning(SAXParseException e) {
                System.out.println("WARNING: " + e);
            }
        });

        // now install the verifying filter
        VerifierFilter filter = verifier.getVerifierFilter();
        SAXReader reader = new SAXReader();
        reader.setxml(标准化越来越近了)Filter(filter);
        return reader;
    }

本文来源于 WEB开发网 原文链接:http://www.cncms.com.cn/ajax/9977.htm




---------------------------------------------------------
专注移动开发
Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian

你可能感兴趣的:([转]Java通过XML Schema校验XML)