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>
xml 校验的更多相关文章
- winform总结4> 工欲善其事,必先利其器之xml校验
@echo 根据xml自动生成xml @echo 当前路径包含空格会导致执行失败 ::pause @echo off set path=%~dp0 for /r %path% %%i in (*.xm ...
- 二十二 XML校验器
Struts2提供的校验器及其规则:
- struts_24_基于XML校验的规则、特点
当为某个action提供了ActionClassName-validation.xml和ActionClassName-ActionName-validation.xml两种规则的校验文件时,系统按下 ...
- 二十一 Struts的数据校验两种方式:手动编码和xml校验
数据的校验: 一.前台校验:JS校验 JS的校验不是必须的,JS可以被绕行,可以提升用户体验 二.后台校验:编码校验 必须的校验 三.校验的方式: 手动编码(不建议使用) 配置文件(支持) 手动编码的 ...
- dubbo配置文件xml校验报错
配置dubbo服务xml后,程序能正常执行,但validate会出现一些异常: Multiple annotations found at this line: - cvc-complex-type. ...
- eclipse spring 配置文件xml校验时,xsd报错
1.情景展示 eclipse中,spring配置文件报错信息如下: 配置文件头部引用信息为: <?xml version="1.0" encoding="UTF ...
- Struts2 基于XML校验(易百教程)
以下是的各类字段级和非字段级验证在Struts2列表: date validator: <field name="birthday"> <field-valida ...
- struts2视频学习笔记 22-23(基于XML配置方式实现对action的所有方法及部分方法进行校验)
课时22 基于XML配置方式实现对action的所有方法进行校验 使用基于XML配置方式实现输入校验时,Action也需要继承ActionSupport,并且提供校验文件,校验文件和action类 ...
- 【Struts2学习笔记(11)】对action的输入校验和XML配置方式实现对action的全部方法进行输入校验
在struts2中,我们能够实现对action的全部方法进行校验或者对action的指定方法进行校验. 对于输入校验struts2提供了两种实现方法: 1. 採用手工编写代码实现. 2. 基于XML配 ...
随机推荐
- 跟阿根一起学Java Web开发二:使用Ajax技术及XML与JSON实现输出
如今B/S结构的系统使用Ajax技术是再平常只是的了.今天我们就来探讨下在JSPGenSDF第四版中:怎样使用Ajax技术.怎样输出XML文件及JSON格式数据输出. 怎样搭建一个最基础的JSPGen ...
- Direct2D 第3篇 绘制文字
原文:Direct2D 第3篇 绘制文字 #include <windows.h> #include <d2d1.h> #include <d2d1helper.h> ...
- koa上传excel文件并解析
1.中间键使用 koa-body npm install koa-body --save const koaBody = require('koa-body'); app.use(koaBody({ ...
- 调试R代码中出现的常用的函数
1. 字符串连接函数 paste的一般使用格式为: paste(..., sep = " ", collapse = NULL) ...表示一个或多个R可以被转化为字符型的对象:s ...
- The 16th UESTC Programming Contest Final 游记
心情不好来写博客. 为了满足ykk想要气球的愿望,NicoDafaGood.Achen和我成功去神大耍了一圈. 因为队名一开始是LargeDumpling应援会,然后队名被和谐,变成了学校的名字,顿时 ...
- 深入浅出Cocoa之消息(二)-详解动态方法决议(Dynamic Method Resolution) 【转】
序言 如果我们在 Objective C 中向一个对象发送它无法处理的消息,会出现什么情况呢?根据前文<深入浅出Cocoa之消息>的介绍,我们知道发送消息是通过 objc_send(id, ...
- 自定义注解--Annotation
Annotation 概念:注解 原理 是一种接口,通过反射机制中的相关API来访问annotation信息 常见的标准Annotation @Override 方法重写 @Deprecated ...
- spring boot + mybatis 访问 neo4j
之前有通过rest的风格去访问,但是每次需要访问时候将statement一并加入header中去数据库执行,方式简单.且思路清晰,但是不便于形成模板调用,固采用mybaits来集成. 1.关键pom. ...
- iOS 9适配
iOS 9系统策略更新,请开发者注意升级 近期苹果公司iOS 9系统策略更新,限制了http协议的访问,此外应用需要在“Info.plist”中将要使用的URL Schemes列为白名单,才可正常检查 ...
- 友盟iOS sdk整理
文档中心 :http://dev.umeng.com 集成文档:http://dev.umeng.com/analytics/ios-doc/integration 报表中心:http://www.u ...