无废话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

相关文章

从基础到高级详解Python数值格式化输出的完全指南

《从基础到高级详解Python数值格式化输出的完全指南》在数据分析、金融计算和科学报告领域,数值格式化是提升可读性和专业性的关键技术,本文将深入解析Python中数值格式化输出的相关方法,感兴趣的小伙... 目录引言:数值格式化的核心价值一、基础格式化方法1.1 三种核心格式化方式对比1.2 基础格式化示例

redis-sentinel基础概念及部署流程

《redis-sentinel基础概念及部署流程》RedisSentinel是Redis的高可用解决方案,通过监控主从节点、自动故障转移、通知机制及配置提供,实现集群故障恢复与服务持续可用,核心组件包... 目录一. 引言二. 核心功能三. 核心组件四. 故障转移流程五. 服务部署六. sentinel部署

从基础到进阶详解Python条件判断的实用指南

《从基础到进阶详解Python条件判断的实用指南》本文将通过15个实战案例,带你大家掌握条件判断的核心技巧,并从基础语法到高级应用一网打尽,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录​引言:条件判断为何如此重要一、基础语法:三行代码构建决策系统二、多条件分支:elif的魔法三、

Python WebSockets 库从基础到实战使用举例

《PythonWebSockets库从基础到实战使用举例》WebSocket是一种全双工、持久化的网络通信协议,适用于需要低延迟的应用,如实时聊天、股票行情推送、在线协作、多人游戏等,本文给大家介... 目录1. 引言2. 为什么使用 WebSocket?3. 安装 WebSockets 库4. 使用 We

从基础到高阶详解Python多态实战应用指南

《从基础到高阶详解Python多态实战应用指南》这篇文章主要从基础到高阶为大家详细介绍Python中多态的相关应用与技巧,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、多态的本质:python的“鸭子类型”哲学二、多态的三大实战场景场景1:数据处理管道——统一处理不同数据格式

MySQL数据类型与表操作全指南( 从基础到高级实践)

《MySQL数据类型与表操作全指南(从基础到高级实践)》本文详解MySQL数据类型分类(数值、日期/时间、字符串)及表操作(创建、修改、维护),涵盖优化技巧如数据类型选择、备份、分区,强调规范设计与... 目录mysql数据类型详解数值类型日期时间类型字符串类型表操作全解析创建表修改表结构添加列修改列删除列

Python 函数详解:从基础语法到高级使用技巧

《Python函数详解:从基础语法到高级使用技巧》本文基于实例代码,全面讲解Python函数的定义、参数传递、变量作用域及类型标注等知识点,帮助初学者快速掌握函数的使用技巧,感兴趣的朋友跟随小编一起... 目录一、函数的基本概念与作用二、函数的定义与调用1. 无参函数2. 带参函数3. 带返回值的函数4.

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

从基础到进阶详解Pandas时间数据处理指南

《从基础到进阶详解Pandas时间数据处理指南》Pandas构建了完整的时间数据处理生态,核心由四个基础类构成,Timestamp,DatetimeIndex,Period和Timedelta,下面我... 目录1. 时间数据类型与基础操作1.1 核心时间对象体系1.2 时间数据生成技巧2. 时间索引与数据

安装centos8设置基础软件仓库时出错的解决方案

《安装centos8设置基础软件仓库时出错的解决方案》:本文主要介绍安装centos8设置基础软件仓库时出错的解决方案,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录安装Centos8设置基础软件仓库时出错版本 8版本 8.2.200android4版本 javas