服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

进阶:看 java 实现的xml schema 验证

最近对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 xmlstring = 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(xmlstring);
            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.setxmlfilter(filter);
        return reader;
    }