xml 校验

package sax.parsing;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXValidator;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

public class ErrorProcessor extends DefaultHandler {

    @Override
    public void warning(SAXParseException exception) throws SAXException {
        System.out.println("触发警告:");
        System.err.println("warning: " + getLocationString(exception) + ": " + exception.getMessage());
    }

    @Override
    public void error(SAXParseException exception) throws SAXException {
        System.out.println("触发错误:");
        System.err.println("error: " + getLocationString(exception) + ": " + exception.getMessage());
    }

    @Override
    public void fatalError(SAXParseException exception) throws SAXException {
        System.out.println("触发致命错误:");
        System.err.println("fatal error: " + getLocationString(exception) + ": " + exception.getMessage());
    }

    private String getLocationString(SAXParseException ex) {
        StringBuffer buffer = new StringBuffer();

        String publicId = ex.getPublicId();
        if (publicId != null) {
            buffer.append(publicId);
            buffer.append("  ");
        }

        String systemId = ex.getSystemId();
        if (systemId != null) {
            buffer.append(systemId);
            buffer.append(‘:‘);
        }

        buffer.append(ex.getLineNumber());
        buffer.append(‘:‘);
        buffer.append(ex.getColumnNumber());

        return buffer.toString();
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.println("</" + qName + ">");
    }

    /**
     *  在DOM文件构建工厂中设置校验Schema文件
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    @Test
    public void parseWithSchema() throws SAXException, IOException, ParserConfigurationException {
        System.out.println("========== parseWithSchema() start ===============");

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(new File("src/students.xsd"));
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setSchema(schema);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        builder.setErrorHandler(new ErrorProcessor());
        Document doc = builder.parse("src/students.xml");

        System.out.println("========== parseWithSchema() end ===============");
    }

    @Test
    public void read() throws FileNotFoundException, IOException, SAXException {

        System.out.println("========== read() start (仅语法校验) ===============");
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setFeature("http://xml.org/sax/features/validation", true);
        xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
        xmlReader.setErrorHandler(new ErrorProcessor());
        xmlReader.parse(new InputSource(new FileInputStream("src/students.xml")));
        System.out.println("========== read() end ===============");
    }

    @Test
    public void saxValidate() throws ParserConfigurationException, SAXException, DocumentException, FileNotFoundException, IOException {
        System.out.println("========== saxValidate() start ===============");

        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setValidating(true); // 等价于 xmlReader.setFeature("http://xml.org/sax/features/validation", true);
        parserFactory.setNamespaceAware(true); // 等价于  reader.setFeature("http://xml.org/sax/features/namespaces",true);

        SAXParser parser = parserFactory.newSAXParser();
        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:/D:/eclipse-luna-jee/workspace/xsl_trans/src/students.xsd");

        XMLReader xmlReader = parser.getXMLReader();
        xmlReader.setErrorHandler(new ErrorProcessor()); // 错误时触发
        //xmlReader.setContentHandler(new ErrorProcessor()); // 标签开始、结束等事件时触发
        xmlReader.parse(new InputSource(new FileInputStream("src/students.xml")));

        System.out.println("========== saxValidate() end ===============");
    }

    @Test
    public void dom4jValidate() throws ParserConfigurationException, SAXException, DocumentException, FileNotFoundException, IOException {
        System.out.println("========== dom4jValidate() start ===============");

        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setValidating(true); // 等价于 xmlReader.setFeature("http://xml.org/sax/features/validation", true);
        parserFactory.setNamespaceAware(true); // 等价于  reader.setFeature("http://xml.org/sax/features/namespaces",true);

        SAXParser parser = parserFactory.newSAXParser();
        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:/D:/eclipse-luna-jee/workspace/xsl_trans/src/students.xsd");

        XMLReader xmlReader = parser.getXMLReader();

        /*
         * dom4j的校验处理过程
         *         org.dom4j.io.SAXReader
         *         org.dom4j.Document
         *         org.dom4j.io.SAXValidator
         */
        SAXReader reader = new SAXReader();
        org.dom4j.Document doc = reader.read(new File("src/students.xml"));

        SAXValidator validator = new SAXValidator(xmlReader);
        validator.setErrorHandler(new ErrorProcessor());
        validator.validate(doc);
        System.out.println("========== dom4jValidate() end ===============");
    }
}

输出:

========== parseWithSchema() start ===============
error: file:///D:/eclipse-luna-jee/workspace/xsl_trans/src/students.xml:4:41: cvc-complex-type.3.2.2: Attribute ‘attr_test‘ is not allowed to appear in element ‘student‘.触发错误:


触发错误:
error: file:///D:/eclipse-luna-jee/workspace/xsl_trans/src/students.xml:10:40: cvc-complex-type.2.4.a: Invalid content was found starting with element ‘elem_test1‘. One of ‘{student}‘ is expected.
========== parseWithSchema() end ===============

========== read() start (仅语法校验) ===============
触发错误:
error: 3:10: Document is invalid: no grammar found.
触发错误:
error: 3:10: Document root element "students", must match DOCTYPE root "null".
========== read() end ===============

========== saxValidate() start ===============
触发错误:
error: 4:41: cvc-complex-type.3.2.2: Attribute ‘attr_test‘ is not allowed to appear in element ‘student‘.
触发错误:
error: 10:40: cvc-complex-type.2.4.a: Invalid content was found starting with element ‘elem_test1‘. One of ‘{student}‘ is expected.
========== saxValidate() end ===============

========== dom4jValidate() start ===============
触发错误:
error: file:///D:/eclipse-luna-jee/workspace/xsl_trans/src/students.xml:3:41: cvc-complex-type.3.2.2: Attribute ‘attr_test‘ is not allowed to appear in element ‘student‘.
触发错误:
error: file:///D:/eclipse-luna-jee/workspace/xsl_trans/src/students.xml:9:39: cvc-complex-type.2.4.a: Invalid content was found starting with element ‘elem_test1‘. One of ‘{student}‘ is expected.
========== dom4jValidate() end ===============

 

students.xml

<?xml version="1.0" encoding="utf-8" ?>

<students>
    <student sn="01" attr_test="errorAttr"><!-- 在student与name父子元素节点之间的是一个文本节点(‘\n\t\t‘) -->
        <name>张三</name>
        <age>18</age>
        <score>100</score>
    </student>

    <elem_test1 attr_test1="errorAttr1" />

    <student sn="02">
        <name>lisi</name>
        <age>20</age>
        <score>100</score>
    </student>

    <elem_test2 attr_test1="errorAttr2" />
</students>

students.xsd

<?xml version="1.0" encoding="utf-8" ?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="students">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="student" type="studentType" maxOccurs="unbounded" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="studentType">
        <xs:sequence>
            <xs:element name="name" type="xs:token" />
            <xs:element name="age" type="xs:positiveInteger" />
            <xs:element name="score" type="xs:float" />
        </xs:sequence>
        <xs:attribute name="sn" type="xs:token" />
    </xs:complexType>
</xs:schema>
时间: 2024-10-09 01:49:17

xml 校验的相关文章

eclipse 解决 xml 校验慢的问题

用于加快 Eclipse xml validator 校验xml的速度. 用Eclipse加载本项目,然后将user_catalog.xml放置在 {workspace}.metadata.plugins\org.eclipse.wst.xml.core下面即可.记得重启Eclipse使变更生效 http://git.oschina.net/oleaster/XMLENTITY 内置了一些xml校验文件,可自己添加.

winform总结4&gt; 工欲善其事,必先利其器之xml校验

@echo 根据xml自动生成xml @echo 当前路径包含空格会导致执行失败 ::pause @echo off set path=%~dp0 for /r %path% %%i in (*.xml) do "xsd.exe" %%i /o:"%path% ::这里的xsd.exe换成你所在电脑上vs中该工具的路径,不想找,可以直接去下边的网盘地址下载. @echo 写入成功 ::@echo 工具通过vs自带sdks 通过xml格式生成对应的校验xsd文件 ::@echo

XML校验之sun.tools.internal.xjc.Driver

最近在用XML做数据对接,用到了XSD文件来对XML进行校验.XSD就是一个规范,对应于这个规范还需要有java代码来对XML处理.可以用sun.tools.internal.xjc.Driver这个类来生成java代码.可以用批处理文件来实现.但是用jdk1.6.0_04会报错,然后换了个版本的jdk就可以了.至今也不知道为什么.(两者的sun.tools.internal.xjc下面都有Drever这个类,有可能是classpath环境变量没有配置好的缘故) 报错信息D:\implement

二十一 Struts的数据校验两种方式:手动编码和xml校验

数据的校验: 一.前台校验:JS校验 JS的校验不是必须的,JS可以被绕行,可以提升用户体验 二.后台校验:编码校验 必须的校验 三.校验的方式: 手动编码(不建议使用) 配置文件(支持) 手动编码的校验方式: 继承ActionSupport,在这个类中写校验方式. 重写validate方法,validate方法在其他业务方法之前执行 针对某个方法校验,需要在方法名应为:validate+方法名,如validateAdd()   validateModify()  validateExecute

Struts2输入校验(XML方式)

本章主要介绍struts2的XML配置方式输入校验.以下将结合一个实例程序进行说明. 代码结构: 关键代码: RegistAction.javapackage com.alfred.regist.action; import java.util.Date; import com.opensymphony.xwork2.ActionSupport; public class RegistAction extends ActionSupport { private static final long

Struts2校验

struts2校验有两种实现方法: 手工编写代码实现(基本验证) //login.jsp <font color="red"><s:fielderror/></font> <s:form action="login"> <s:textfield name="uname" label="user name"></s:textfield> <s:pass

XML小结

一.XML概述 英文全称为Extensible Markup Language,翻译过来为可扩展标记语言.XML技术是W3C组织发布的,目前遵循的是W3C组织于2000发布的XML1.0规范.XML就是为了解决这样的需求而产生数据存储格式. 在XML语言中,它允许用户自定义标签.每一个标签用于描述一段数据:一个标签可以分为开始标签和结束标签,在开始标签和结束标签之间又可以嵌套其它标签,利用标签间的嵌套关系来保存数据之间的上下级关系:由于xml实质上是一段字符串,计算机可以十分方便的对他进行操作,

struts2校验细节

使用struts2框架进行输入校验,主要步骤: ①准备实体类 package com.struts2.validate.entities; public class User { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge(

C#使用xsd文件验证XML 格式是否正确

方法一: 我使用XmlReader来处理,因为觉得XmlReader简单点. 我自己做了个例子来说明,例子里的XML不是很复杂,没有子节点的. XML 文件(a.xml): <?xml version="1.0" encoding="utf-8" ?> <PROFILE> <PROFILEID>0001</PROFILEID> <DESCIPTION>我的内容</DESCIPTION> <