SAX轻松入门(二)--带验证的SAX解析

 /*java and xml 3nd学习笔记
SAX轻松入门(二)--带验证的SAX解析
author:shine
*/
继续SAX轻松入门(一)中的例子Test1,本文中主要只解决一个问题:
1)SAX轻松入门(一)中简单的介绍了不带验证的SAX解析,那么带验证的呢?


NO1.
SAX中的验证不像JAXP中有setValidation()方法,也不是用一个专门的类(javax.xml.validation)进行验证,到底是怎么样的呢?

先准备一个xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!--Sample XML file generated by XMLSpy v2007 (http://www.altova.com)-->
<poem xmlns="http://www.shine.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.shine.com test1.xsd">
 <title titleId="1">Roses are Red</title>
 <i>Roses are red,</i>
 <i>Violets are blue;</i>
 <i>Sugar is sweet,</i>
 <i>And I love you</i>
</poem>


再准备一个schema(test1.xsd):
<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSpy v2007 (http://www.altova.com) by shine (EMBRACE) -->
<xs:schema xmlns="http://www.shine.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.shine.com" elementFormDefault="qualified">
 <xs:element name="poem">
  <xs:complexType>
   <xs:sequence>
    <xs:element name="title">
     <xs:complexType>
      <xs:simpleContent>
       <xs:extension base="xs:string">
        <xs:attribute name="titleId" type="xs:string" use="required"/>
       </xs:extension>
      </xs:simpleContent>
     </xs:complexType>
    </xs:element>
    <xs:element name="i" type="xs:string" maxOccurs="unbounded"/>
   </xs:sequence>
  </xs:complexType>
 </xs:element>
</xs:schema>

 

改装一下类Test1(参看“SAX轻松入门(一)”)的main函数进行验证:
....
XMLReader reader = XMLReaderFactory.CreateXMLReaderFactory();
String featureURI = "";
.....
featureURI = "http://xml.org/sax/features/validation";
reader.setFeature(featureURI, true);  //打开普通验证
featureURI = "http://apache.org/xml/features/validation/schema";
reader.setFeature(featureURI, true);  //打开schema验证
.....

这下,验证是验证了,但怎么错了也没看到“反应”啊,这就引出了第二个问题。


NO2
我们如何处理错误呢?在SAX中使用四大接口之一的ErrorHandler处理错误。只要实现ErrorHandler,那么就能对“错误”进行监控。通常可以写“错误”日志
如:
package test;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class Test1Validation implements ErrorHandler{

 public void error(SAXParseException exception) throws SAXException {
  // 处理出现的非致命错误(一般是“有效性”的问题)
  try {
   FileWriter fw = new FileWriter("D://workplace//errorLog.log",true);
   BufferedWriter bw = new BufferedWriter(fw);
   bw.write("error "+exception.getLineNumber() + ": " + exception.getMessage()+"/r/n/r/n");
   bw.flush();
   bw.close();
   fw.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
 }

 public void fatalError(SAXParseException exception) throws SAXException {
  // 处理出现的致命错误(一般是“well-form”的问题)
  try {
   FileWriter fw = new FileWriter("D://workplace//errorLog.log",true);
   BufferedWriter bw = new BufferedWriter(fw);
   bw.write("fatalError "+exception.getLineNumber() + ": " + exception.getMessage()+"/r/n/r/n");
   bw.flush();
   bw.close();
   fw.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 public void warning(SAXParseException exception) throws SAXException {
  // 处理程序的警告
  try {
   FileWriter fw = new FileWriter("D://workplace//errorLog.log",true);
   BufferedWriter bw = new BufferedWriter(fw);
   bw.write("warning "+exception.getLineNumber() + ": " + exception.getMessage()+"/r/n/r/n");
   bw.flush();
   bw.close();
   fw.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}


然后就是在Test1(参看“SAX轻松入门(一)”)的主函数进行ErrorHandler的注册。
如:
 public static void main(String[] args) {
  String xmlURI = "D://workplace//test1.xml";
  String featureURI = "";
  try {
   XMLReader reader = XMLReaderFactory.createXMLReader();
   Test1 test1 = new Test1();
   reader.setContentHandler(test1);  //注册ContentHandler,即:使用test1对象来处理“content”
   Test1Validation test1Validation = new Test1Validation(); //声明处理错误的类************
   reader.setErrorHandler(test1Validation);  //进行ErrorHandler的注册***************
   featureURI = "http://xml.org/sax/features/validation";
   reader.setFeature(featureURI, true);  //打开普通验证
   featureURI = "http://apache.org/xml/features/validation/schema";
   reader.setFeature(featureURI, true);  //打开schema验证
   BufferedReader br = new BufferedReader(new FileReader(xmlURI));  
   InputSource inputSource = new InputSource(br);
   inputSource.setSystemId(xmlURI);
   reader.parse(inputSource);
   br.close();
   
  } catch (SAXException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 

NO3
试验一下:
1)如果在xml中加入<a/>
则在errorLog.log中应该有:
error 5: cvc-complex-type.2.4.a: Invalid content starting with element 'a'. The content must match '(("http://www.shine.com":title),("http://www.shine.com":i){1-UNBOUNDED})'.
(“有效性”问题触发error事件)

2)如果在xml中的<i>And I love you</i>变为:<iAnd I love you</i>   (掉了一个">",)
则在errorLog.log中应该有:
fatalError 7: Attribute name "is" must be followed by the ' = ' character.
(“格式”问题触发fatalError事件)


NO4
还得注意一点(非常重要),在xml根元素的属性中
xsi:schemaLocation="http://www.shine.com test1.xsd",
在拼写Location时,绝对不能出现反斜杠,如:
xsi:schemaLocation="http://www.shine.com D:/workplace/test1.xsd",后果是:
error 3: cvc-datatype-valid.1.2.1: 'D:/workplace/test1.xsd' is not a valid 'anyURI' value.

error 3: cvc-attribute.3: The value 'http://www.shine.com D:/workplace/test1.xsd' of attribute 'xsi:schemaLocation' on element 'poem' is not valid with respect to its type.
所以最好把xml文件和schema放在一起。(不用写全路径)


/*
SAX轻松入门(三)--SAX过滤器(Filter)  2008-2-15
*/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值