1. package sax.parsing;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7.  
  8. import javax.xml.XMLConstants;
  9. import javax.xml.parsers.DocumentBuilder;
  10. import javax.xml.parsers.DocumentBuilderFactory;
  11. import javax.xml.parsers.ParserConfigurationException;
  12. import javax.xml.parsers.SAXParser;
  13. import javax.xml.parsers.SAXParserFactory;
  14. import javax.xml.validation.Schema;
  15. import javax.xml.validation.SchemaFactory;
  16.  
  17. import org.dom4j.DocumentException;
  18. import org.dom4j.io.SAXReader;
  19. import org.dom4j.io.SAXValidator;
  20. import org.testng.annotations.Test;
  21. import org.w3c.dom.Document;
  22. import org.xml.sax.InputSource;
  23. import org.xml.sax.SAXException;
  24. import org.xml.sax.SAXParseException;
  25. import org.xml.sax.XMLReader;
  26. import org.xml.sax.helpers.DefaultHandler;
  27. import org.xml.sax.helpers.XMLReaderFactory;
  28.  
  29. public class ErrorProcessor extends DefaultHandler {
  30.  
  31. @Override
  32. public void warning(SAXParseException exception) throws SAXException {
  33. System.out.println("触发警告:");
  34. System.err.println("warning: " + getLocationString(exception) + ": " + exception.getMessage());
  35. }
  36.  
  37. @Override
  38. public void error(SAXParseException exception) throws SAXException {
  39. System.out.println("触发错误:");
  40. System.err.println("error: " + getLocationString(exception) + ": " + exception.getMessage());
  41. }
  42.  
  43. @Override
  44. public void fatalError(SAXParseException exception) throws SAXException {
  45. System.out.println("触发致命错误:");
  46. System.err.println("fatal error: " + getLocationString(exception) + ": " + exception.getMessage());
  47. }
  48.  
  49. private String getLocationString(SAXParseException ex) {
  50. StringBuffer buffer = new StringBuffer();
  51.  
  52. String publicId = ex.getPublicId();
  53. if (publicId != null) {
  54. buffer.append(publicId);
  55. buffer.append(" ");
  56. }
  57.  
  58. String systemId = ex.getSystemId();
  59. if (systemId != null) {
  60. buffer.append(systemId);
  61. buffer.append(':');
  62. }
  63.  
  64. buffer.append(ex.getLineNumber());
  65. buffer.append(':');
  66. buffer.append(ex.getColumnNumber());
  67.  
  68. return buffer.toString();
  69. }
  70.  
  71. @Override
  72. public void endElement(String uri, String localName, String qName) throws SAXException {
  73. System.out.println("</" + qName + ">");
  74. }
  75.  
  76. /**
  77. * 在DOM文件构建工厂中设置校验Schema文件
  78. * @throws IOException
  79. * @throws SAXException
  80. * @throws ParserConfigurationException
  81. */
  82. @Test
  83. public void parseWithSchema() throws SAXException, IOException, ParserConfigurationException {
  84. System.out.println("========== parseWithSchema() start ===============");
  85.  
  86. SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  87. Schema schema = schemaFactory.newSchema(new File("src/students.xsd"));
  88. DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
  89. builderFactory.setSchema(schema);
  90. DocumentBuilder builder = builderFactory.newDocumentBuilder();
  91. builder.setErrorHandler(new ErrorProcessor());
  92. Document doc = builder.parse("src/students.xml");
  93.  
  94. System.out.println("========== parseWithSchema() end ===============");
  95. }
  96.  
  97. @Test
  98. public void read() throws FileNotFoundException, IOException, SAXException {
  99.  
  100. System.out.println("========== read() start (仅语法校验) ===============");
  101. XMLReader xmlReader = XMLReaderFactory.createXMLReader();
  102. xmlReader.setFeature("http://xml.org/sax/features/validation", true);
  103. xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
  104. xmlReader.setErrorHandler(new ErrorProcessor());
  105. xmlReader.parse(new InputSource(new FileInputStream("src/students.xml")));
  106. System.out.println("========== read() end ===============");
  107. }
  108.  
  109. @Test
  110. public void saxValidate() throws ParserConfigurationException, SAXException, DocumentException, FileNotFoundException, IOException {
  111. System.out.println("========== saxValidate() start ===============");
  112.  
  113. SAXParserFactory parserFactory = SAXParserFactory.newInstance();
  114. parserFactory.setValidating(true); // 等价于 xmlReader.setFeature("http://xml.org/sax/features/validation", true);
  115. parserFactory.setNamespaceAware(true); // 等价于 reader.setFeature("http://xml.org/sax/features/namespaces",true);
  116.  
  117. SAXParser parser = parserFactory.newSAXParser();
  118. parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
  119. parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:/D:/eclipse-luna-jee/workspace/xsl_trans/src/students.xsd");
  120.  
  121. XMLReader xmlReader = parser.getXMLReader();
  122. xmlReader.setErrorHandler(new ErrorProcessor()); // 错误时触发
  123. //xmlReader.setContentHandler(new ErrorProcessor()); // 标签开始、结束等事件时触发
  124. xmlReader.parse(new InputSource(new FileInputStream("src/students.xml")));
  125.  
  126. System.out.println("========== saxValidate() end ===============");
  127. }
  128.  
  129. @Test
  130. public void dom4jValidate() throws ParserConfigurationException, SAXException, DocumentException, FileNotFoundException, IOException {
  131. System.out.println("========== dom4jValidate() start ===============");
  132.  
  133. SAXParserFactory parserFactory = SAXParserFactory.newInstance();
  134. parserFactory.setValidating(true); // 等价于 xmlReader.setFeature("http://xml.org/sax/features/validation", true);
  135. parserFactory.setNamespaceAware(true); // 等价于 reader.setFeature("http://xml.org/sax/features/namespaces",true);
  136.  
  137. SAXParser parser = parserFactory.newSAXParser();
  138. parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
  139. parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:/D:/eclipse-luna-jee/workspace/xsl_trans/src/students.xsd");
  140.  
  141. XMLReader xmlReader = parser.getXMLReader();
  142.  
  143. /*
  144. * dom4j的校验处理过程
  145. * org.dom4j.io.SAXReader
  146. * org.dom4j.Document
  147. * org.dom4j.io.SAXValidator
  148. */
  149. SAXReader reader = new SAXReader();
  150. org.dom4j.Document doc = reader.read(new File("src/students.xml"));
  151.  
  152. SAXValidator validator = new SAXValidator(xmlReader);
  153. validator.setErrorHandler(new ErrorProcessor());
  154. validator.validate(doc);
  155. System.out.println("========== dom4jValidate() end ===============");
  156. }
  157. }
  158.  
  159. 输出:

========== 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'.触发错误:

  1.  

触发错误:
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 ===============

  1.  

students.xml

  1. <?xml version="1.0" encoding="utf-8" ?>
  2.  
  3. <students>
  4. <student sn="01" attr_test="errorAttr"><!-- 在student与name父子元素节点之间的是一个文本节点('\n\t\t') -->
  5. <name>张三</name>
  6. <age>18</age>
  7. <score>100</score>
  8. </student>
  9.  
  10. <elem_test1 attr_test1="errorAttr1" />
  11.  
  12. <student sn="02">
  13. <name>lisi</name>
  14. <age>20</age>
  15. <score>100</score>
  16. </student>
  17.  
  18. <elem_test2 attr_test1="errorAttr2" />
  19. </students>

students.xsd

  1. <?xml version="1.0" encoding="utf-8" ?>
  2.  
  3. <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  4. <xs:element name="students">
  5. <xs:complexType>
  6. <xs:sequence>
  7. <xs:element name="student" type="studentType" maxOccurs="unbounded" />
  8. </xs:sequence>
  9. </xs:complexType>
  10. </xs:element>
  11.  
  12. <xs:complexType name="studentType">
  13. <xs:sequence>
  14. <xs:element name="name" type="xs:token" />
  15. <xs:element name="age" type="xs:positiveInteger" />
  16. <xs:element name="score" type="xs:float" />
  17. </xs:sequence>
  18. <xs:attribute name="sn" type="xs:token" />
  19. </xs:complexType>
  20. </xs:schema>

xml 校验的更多相关文章

  1. winform总结4> 工欲善其事,必先利其器之xml校验

    @echo 根据xml自动生成xml @echo 当前路径包含空格会导致执行失败 ::pause @echo off set path=%~dp0 for /r %path% %%i in (*.xm ...

  2. 二十二 XML校验器

    Struts2提供的校验器及其规则:

  3. struts_24_基于XML校验的规则、特点

    当为某个action提供了ActionClassName-validation.xml和ActionClassName-ActionName-validation.xml两种规则的校验文件时,系统按下 ...

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

    数据的校验: 一.前台校验:JS校验 JS的校验不是必须的,JS可以被绕行,可以提升用户体验 二.后台校验:编码校验 必须的校验 三.校验的方式: 手动编码(不建议使用) 配置文件(支持) 手动编码的 ...

  5. dubbo配置文件xml校验报错

    配置dubbo服务xml后,程序能正常执行,但validate会出现一些异常: Multiple annotations found at this line: - cvc-complex-type. ...

  6. eclipse spring 配置文件xml校验时,xsd报错

      1.情景展示 eclipse中,spring配置文件报错信息如下: 配置文件头部引用信息为: <?xml version="1.0" encoding="UTF ...

  7. Struts2 基于XML校验(易百教程)

    以下是的各类字段级和非字段级验证在Struts2列表: date validator: <field name="birthday"> <field-valida ...

  8. struts2视频学习笔记 22-23(基于XML配置方式实现对action的所有方法及部分方法进行校验)

    课时22 基于XML配置方式实现对action的所有方法进行校验   使用基于XML配置方式实现输入校验时,Action也需要继承ActionSupport,并且提供校验文件,校验文件和action类 ...

  9. 【Struts2学习笔记(11)】对action的输入校验和XML配置方式实现对action的全部方法进行输入校验

    在struts2中,我们能够实现对action的全部方法进行校验或者对action的指定方法进行校验. 对于输入校验struts2提供了两种实现方法: 1. 採用手工编写代码实现. 2. 基于XML配 ...

随机推荐

  1. javascript中uber实现子类访问父类成员

    function Animal(){} Animal.prototype={ name:"animal", toString:function(){ console.log(thi ...

  2. screen 基础用法(转)

    ####################### 屏幕分割 ######################## 1. screen2. Ctrl-a c    # create a new screen3 ...

  3. Leetcode720.Longest Word in Dictionary词典中最长的单词

    给出一个字符串数组words组成的一本英语词典.从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成.若其中有多个可行的答案,则返回答案中字典序最小的单词. 若无答案,则返回 ...

  4. Leetcode695.Max Area of Island岛屿的最大面积

    给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合.你可以假设二维矩阵的四个边缘都被水包围着. 找到给定的二维数组中 ...

  5. BZOJ2770: YY的Treap

    原本看标题还以为是treap的题,但是实际上是线段树. 求两点的LCA相当于求区间priority最小值的位置. 然后就可以离线先离散化然后建树做了. 记录的minpos是线段树上叶子结点的节点编号. ...

  6. Mysql主从安装配置

    Mysql主从安装配置   环境: 主从服务器上的MySQL数据库版本同为5.1.34 主机IP:192.168.0.1 从机IP:192.168.0.2  一. MySQL主服务器配置 1.编辑配置 ...

  7. Thrift源码分析(一)-- 基本概念

    我所在的公司使用Thrift作为基础通信组件,相当一部分的RPC服务基于Thrift框架.公司的日UV在千万级别,Thrift很好地支持了高并发访问,并且Thrift相对简单地编程模型也提高了服务地开 ...

  8. 【JZOJ4811】【NOIP2016提高A组五校联考1】排队

    题目描述 输入 输出 样例输入 5 4 1 2 1 3 3 4 3 5 1 4 2 4 1 2 2 5 样例输出 3 1 1 2 数据范围 样例解释 解法 可推知原树可以转换为一个序列,即优先序列: ...

  9. Tumblr,instapaper分享

    <div id="bshare-custom"> <a title="分享到Tumblr" id="bshare-tumblr&qu ...

  10. Django1.11使用命令makemigrations提示No Changes

    在项目中,遇到models模型变动,变动后合并发生问题,故当时做了删除应用文件夹下migrations文件,由于数据库里无较多新数据,故删除后重建,但重建后执行模型合并操作结果为No Changes, ...