无废话SAX:十分钟了解sax基础

2024-04-27 22:32

本文主要是介绍无废话SAX:十分钟了解sax基础,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Sax 是事件驱动的 xml 简单接口。

要解析一份 xml 文档,而且在解析的过程中当某些事件发生时执行你希望此时执行的代码,就先准备以下三件事情。

l         获取一个 xml 解析器:到 xml.apache.org 免费获取。

l         获取 sax 类:上述的 xerces 解析器已经包括了,记得在 classpath 里包括他们。

l         获取一个 xml 文档:相信这个你自己可以搞定

接下来的事情,我认为以下的代码基本上说明了流程,其中要稍微解释的是 ContentHandler 接口。 SAX 2.0 定义了四个核心的处理接口,分别是 ContentHandler ErrorHandler DTDHandler EntityResolver 。其中较常用到的是前面两个,最后一个是处理 xml 里的实体的,而在 schema 较流行的今天, DTDHandler 也许不太需要注意。这些处理器可以被 set parser 上,当 parser 在解析 xml 文档的过程中,发生特定的事件时,处理器中对应的方法便会被调用,当然了,方法的内容由你来写。这个基本上就是 sax 的概要情况了。

在读完代码和自己运行过下面的代码后,我相信你对 sax 的工作方式已经了解了,剩下的事情就是自己去熟悉另外几个处理器的方法。希望这篇东西能让你快速了解 sax ,而还有不少的细节,还需要自己去慢慢探讨了。

public   class  Practice1 {

 

       
// 要实例化的reader的类名

       
private  String vendroParserClass  =   " org.apache.xerces.parsers.SAXParser " ;

 

       
// 被读取的xml文件路径,以bin为根目录。

       
private  String uri  =   " xmlDocuments/xmlPractise.xml " ;

 

       
// 为0时debugPrint方法不会打印数据。

       
private   final   int  debug  =   1 ;

 

       
public   void  test()  throws  IOException, SAXException {

              XMLReader reader 
=   null ;

              
try  {

                     
// 工厂方法以类名获得reader实例

                     reader 
=  XMLReaderFactory.createXMLReader(vendroParserClass);

              } 
catch  (Exception e) {

                     e.printStackTrace();

              }

              
// 以uri获取xml文档实例,reader.parse()方法可以接受一个

              // 简单的uri作为参数,但是InputSource会更好。

              InputSource inputSource 
=   new  InputSource(uri);

              
// 设置contentHandler

              reader.setContentHandler(
new  MyContentHandler());

              
// 执行读取

              reader.parse(inputSource);

              System.out.println(
" test completed. " );

       }

 

       
public   void  debugPrint(String msg) {

              
if  (debug  >   0 ) {

                     System.out.print(msg);

              }

       }

       
// 内容处理器

       
class  MyContentHandler  implements  ContentHandler {

              
// locator是定位器,指示当前解析文档进行到哪个位置了。

             // 它只在解析生命周期内有效,解析完毕就别再碰它咯~

              
private  Locator locator;

 

              
// 这个方法在整个解析过程的一开始被调用

public   void  setDocumentLocator(Locator locator) {

                     debugPrint(
" setDocumentLocator get called./n " );

                     
this .locator  =  locator;

              }

              

               // xml文档开始时被调用

              
public   void  startDocument()  throws  SAXException {

                     debugPrint(
" startDocument() get called./n " );

 

              }

              
// xml文档结束时被调用

              
public   void  endDocument()  throws  SAXException {

                     debugPrint(
" endDocument() get called./n " );

 

              }

               // xml文档的某个名称空间开始时被调用

              
public   void  startPrefixMapping(String prefix, String uri)

                            
throws  SAXException {

                     debugPrint(
" start of : uri:  "   +  uri  +   " , prefix:  "   +  prefix  +   " ./n " );

 

              }

              
// xml文档的某个名称空间结束时被调用

              
public   void  endPrefixMapping(String prefix)  throws  SAXException {

                     debugPrint(
" end of: uri:  "   +  uri  +   " , prefix:  "   +  prefix  +   " ./n " );

 

              }

              
// xml文档的某个元素开始时被调用

              
// uri是名称空间,localName是不带前缀的元素名,qName是前缀+元素名

              
// atts就是属性列表了。

              
public   void  startElement(String uri, String localName, String qName,

                            Attributes atts) 
throws  SAXException {

                     debugPrint(
" < "   +  localName  +   " > " );

 

              }

              
// xml文档的某个元素结束时被调用

              
public   void  endElement(String uri, String localName, String qName)

                            
throws  SAXException {

                     debugPrint(
" </ "   +  localName  +   " > " );

 

              }

              
// xml文档的某个元素的文本内容出现时被调用

            // start和length是字符串截取的开始位置和长度,如下所示是比较好的

               // 处理方法,先转换成String再处理

              
public   void  characters( char [] ch,  int  start,  int  length)

                            
throws  SAXException {

                     String s 
=   new  String(ch, start, length);

                     debugPrint(s);

                     

              }

            // 遇到可以忽略的空白时被调用,关于xml里的空白,可以长篇大论,

            // 这里就不废话了。

              
public   void  ignorableWhitespace( char [] ch,  int  start,  int  length)

                            
throws  SAXException {

                     
//  TODO Auto-generated method stub

 

              }

              
// 遇到xml的处理指令时被调用

              
public   void  processingInstruction(String target, String data)

                            
throws  SAXException {

                     debugPrint(
" PI target: ' "   +  target  +   " ', data: ' "   +  data  +   " '. " );

 

              }

              
// 当xml里的实体被非验证解析器忽略时被调用

              
public   void  skippedEntity(String name)  throws  SAXException {

                     
//  TODO Auto-generated method stub

 

              }

 

       }

 

       
public   static   void  main(String[] args)  throws  IOException, SAXException {

              
new  Practice1().test();

       }

}


题外话:以自己的学习的经历,感觉接触一门新技术的时候,详尽的经典著作未必最合适,如果要追求平缓的学习曲线,最好的方法是听学过的人谈谈整体的概念,看看运作实例,此时心中有了感性认识,再投入真正的学习中去,效果相当好。这也是写这篇东西的初衷了。文章很简陋,望勿见笑。


SAX is a event-driven simple api for xml.

There are three things to get before using SAX to parse a xml document, and make some code to execute when certain events comes up.

l        Get an xml parser: download it from xml.apache.org for free.

l        Get a SAX class: it should be included in the parser we mentioned above.

l        Get an xml document: get the white mouse yourself.

 

The following is quite self-explanative, the codes describe the basic flow. Only the ContentHandler interface needs a little bit words. SAX 2.0 defined 4 core handler interfaces: ContentHandler, ErrorHandler, DTDHandler, EntityResolver. The leading 2 are often used, the last one is for the entity in xml, while schema is more prefer now, DTDHandler needs not much attention. These handlers can be set to a parser, when the parser is parsing the xml file, some certain events take places, the corresponding methods will be called back. The content in these methods, of course, will be finished by you, that’s what call-back is. Then it is the brief of SAX.

After reading and running the following codes, I believed that you are clear about how SAX works, what’s left is that you shall get familiar with other handlers. I hope this stuff can help you understand SAX in a short time, the details are left to yourself.

 

 

public   class  Practice1 {

 

       
// name of the reader class that will be initialled.

       
private  String vendroParserClass  =   " org.apache.xerces.parsers.SAXParser " ;

 

       
// file path of the xml file,using bin as file root 。

       
private  String uri  =   " xmlDocuments/xmlPractise.xml " ;

 

       
// when this equasl 0, debugPrint() method won’t print message out。

       
private   final   int  debug  =   1 ;

 

       
public   void  test()  throws  IOException, SAXException {

              XMLReader reader 
=   null ;

              
try  {

                     
// using factory pattern 

                     reader 
=  XMLReaderFactory.createXMLReader(vendroParserClass);

              } 
catch  (Exception e) {

                     e.printStackTrace();

              }

              
// get a xml file instance using uri,reader.parse()method can accept a simple 

//  uri as a parameter, but InputSource is better。

              InputSource inputSource 
=   new  InputSource(uri);

              
// set the contentHandler

              reader.setContentHandler(
new  MyContentHandler());

              
// executing the parsing

              reader.parse(inputSource);

              System.out.println(
" test completed. " );

       }

 

       
public   void  debugPrint(String msg) {

              
if  (debug  >   0 ) {

                     System.out.print(msg);

              }

       }

       
// content handler

       
class  MyContentHandler  implements  ContentHandler {

              
// locator indicate the current position when parsing the file

// it is only valid during parsing, so don’t touch it after the parsing is finished

              
private  Locator locator;

 

              
// this method will be the first method called as the parsing begins.

public   void  setDocumentLocator(Locator locator) {

                     debugPrint(
" setDocumentLocator get called./n " );

                     
this .locator  =  locator;

              }

              

// this method will be called at the start of a xml file 

              
public   void  startDocument()  throws  SAXException {

                     debugPrint(
" startDocument() get called./n " );

 

              }

              
//  this method will be called at the end of a xml file

              
public   void  endDocument()  throws  SAXException {

                     debugPrint(
" endDocument() get called./n " );

 

              }

//  this method will be called at the start of a namespace

              
public   void  startPrefixMapping(String prefix, String uri)

                            
throws  SAXException {

                     debugPrint(
" start of : uri:  "   +  uri  +   " , prefix:  "   +  prefix  +   " ./n " );

 

              }

              
//  this method will be called at the end of a namespace

              
public   void  endPrefixMapping(String prefix)  throws  SAXException {

                     debugPrint(
" end of: uri:  "   +  uri  +   " , prefix:  "   +  prefix  +   " ./n " );

 

              }

              
//  this method will be called at the start of an element

              
public   void  startElement(String uri, String localName, String qName,

                            Attributes atts) 
throws  SAXException {

                     debugPrint(
" < "   +  localName  +   " > " );

 

              }

              
//  this method will be called at the end of an element

              
public   void  endElement(String uri, String localName, String qName)

                            
throws  SAXException {

                     debugPrint(
" </ "   +  localName  +   " > " );

 

              }

              
// x this method will be called when the text content appears

// start and length is the start index and length of the char array.

// parsed to a String before handling the content will be a good choice

              
public   void  characters( char [] ch,  int  start,  int  length)

                            
throws  SAXException {

                     String s 
=   new  String(ch, start, length);

                     debugPrint(s);

                     

              }

//  this method will be called when some ignorable white space appears,

//  there are much to talk about white space in xml, we aren’t talking them here.

              
public   void  ignorableWhitespace( char [] ch,  int  start,  int  length)

                            
throws  SAXException {

                     
//  TODO Auto-generated method stub

 

              }

              
//  this method will be called when processing instructions appears

              
public   void  processingInstruction(String target, String data)

                            
throws  SAXException {

                     debugPrint(
" PI target: ' "   +  target  +   " ', data: ' "   +  data  +   " '. " );

 

              }

//  this method will be called when the entity in the xml file is skipped by the  // parser.

              
public   void  skippedEntity(String name)  throws  SAXException {

                     
//  TODO Auto-generated method stub

 

              }

 

       }

 

       
public   static   void  main(String[] args)  throws  IOException, SAXException {

              
new  Practice1().test();

       }

}

这篇关于无废话SAX:十分钟了解sax基础的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/941702

相关文章

Android Mainline基础简介

《AndroidMainline基础简介》AndroidMainline是通过模块化更新Android核心组件的框架,可能提高安全性,本文给大家介绍AndroidMainline基础简介,感兴趣的朋... 目录关键要点什么是 android Mainline?Android Mainline 的工作原理关键

mysql的基础语句和外键查询及其语句详解(推荐)

《mysql的基础语句和外键查询及其语句详解(推荐)》:本文主要介绍mysql的基础语句和外键查询及其语句详解(推荐),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录一、mysql 基础语句1. 数据库操作 创建数据库2. 表操作 创建表3. CRUD 操作二、外键

Python基础语法中defaultdict的使用小结

《Python基础语法中defaultdict的使用小结》Python的defaultdict是collections模块中提供的一种特殊的字典类型,它与普通的字典(dict)有着相似的功能,本文主要... 目录示例1示例2python的defaultdict是collections模块中提供的一种特殊的字

Python基础文件操作方法超详细讲解(详解版)

《Python基础文件操作方法超详细讲解(详解版)》文件就是操作系统为用户或应用程序提供的一个读写硬盘的虚拟单位,文件的核心操作就是读和写,:本文主要介绍Python基础文件操作方法超详细讲解的相... 目录一、文件操作1. 文件打开与关闭1.1 打开文件1.2 关闭文件2. 访问模式及说明二、文件读写1.

C#基础之委托详解(Delegate)

《C#基础之委托详解(Delegate)》:本文主要介绍C#基础之委托(Delegate),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. 委托定义2. 委托实例化3. 多播委托(Multicast Delegates)4. 委托的用途事件处理回调函数LINQ

一文带你了解SpringBoot中启动参数的各种用法

《一文带你了解SpringBoot中启动参数的各种用法》在使用SpringBoot开发应用时,我们通常需要根据不同的环境或特定需求调整启动参数,那么,SpringBoot提供了哪些方式来配置这些启动参... 目录一、启动参数的常见传递方式二、通过命令行参数传递启动参数三、使用 application.pro

一文带你深入了解Python中的GeneratorExit异常处理

《一文带你深入了解Python中的GeneratorExit异常处理》GeneratorExit是Python内置的异常,当生成器或协程被强制关闭时,Python解释器会向其发送这个异常,下面我们来看... 目录GeneratorExit:协程世界的死亡通知书什么是GeneratorExit实际中的问题案例

0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型的操作流程

《0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeekR1模型的操作流程》DeepSeekR1模型凭借其强大的自然语言处理能力,在未来具有广阔的应用前景,有望在多个领域发... 目录0基础租个硬件玩deepseek,蓝耘元生代智算云|本地部署DeepSeek R1模型,3步搞定一个应

MySQL中my.ini文件的基础配置和优化配置方式

《MySQL中my.ini文件的基础配置和优化配置方式》文章讨论了数据库异步同步的优化思路,包括三个主要方面:幂等性、时序和延迟,作者还分享了MySQL配置文件的优化经验,并鼓励读者提供支持... 目录mysql my.ini文件的配置和优化配置优化思路MySQL配置文件优化总结MySQL my.ini文件

关于数据埋点,你需要了解这些基本知识

产品汪每天都在和数据打交道,你知道数据来自哪里吗? 移动app端内的用户行为数据大多来自埋点,了解一些埋点知识,能和数据分析师、技术侃大山,参与到前期的数据采集,更重要是让最终的埋点数据能为我所用,否则可怜巴巴等上几个月是常有的事。   埋点类型 根据埋点方式,可以区分为: 手动埋点半自动埋点全自动埋点 秉承“任何事物都有两面性”的道理:自动程度高的,能解决通用统计,便于统一化管理,但个性化定