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

相关文章

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

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

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

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

Linux基础命令@grep、wc、管道符的使用详解

《Linux基础命令@grep、wc、管道符的使用详解》:本文主要介绍Linux基础命令@grep、wc、管道符的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录grep概念语法作用演示一演示二演示三,带选项 -nwc概念语法作用wc,不带选项-c,统计字节数-

python操作redis基础

《python操作redis基础》Redis(RemoteDictionaryServer)是一个开源的、基于内存的键值对(Key-Value)存储系统,它通常用作数据库、缓存和消息代理,这篇文章... 目录1. Redis 简介2. 前提条件3. 安装 python Redis 客户端库4. 连接到 Re

SpringBoot基础框架详解

《SpringBoot基础框架详解》SpringBoot开发目的是为了简化Spring应用的创建、运行、调试和部署等,使用SpringBoot可以不用或者只需要很少的Spring配置就可以让企业项目快... 目录SpringBoot基础 – 框架介绍1.SpringBoot介绍1.1 概述1.2 核心功能2

Spring Boot集成SLF4j从基础到高级实践(最新推荐)

《SpringBoot集成SLF4j从基础到高级实践(最新推荐)》SLF4j(SimpleLoggingFacadeforJava)是一个日志门面(Facade),不是具体的日志实现,这篇文章主要介... 目录一、日志框架概述与SLF4j简介1.1 为什么需要日志框架1.2 主流日志框架对比1.3 SLF4

Spring Boot集成Logback终极指南之从基础到高级配置实战指南

《SpringBoot集成Logback终极指南之从基础到高级配置实战指南》Logback是一个可靠、通用且快速的Java日志框架,作为Log4j的继承者,由Log4j创始人设计,:本文主要介绍... 目录一、Logback简介与Spring Boot集成基础1.1 Logback是什么?1.2 Sprin

MySQL复合查询从基础到多表关联与高级技巧全解析

《MySQL复合查询从基础到多表关联与高级技巧全解析》本文主要讲解了在MySQL中的复合查询,下面是关于本文章所需要数据的建表语句,感兴趣的朋友跟随小编一起看看吧... 目录前言:1.基本查询回顾:1.1.查询工资高于500或岗位为MANAGER的雇员,同时还要满足他们的姓名首字母为大写的J1.2.按照部门

一文详解Java异常处理你都了解哪些知识

《一文详解Java异常处理你都了解哪些知识》:本文主要介绍Java异常处理的相关资料,包括异常的分类、捕获和处理异常的语法、常见的异常类型以及自定义异常的实现,文中通过代码介绍的非常详细,需要的朋... 目录前言一、什么是异常二、异常的分类2.1 受检异常2.2 非受检异常三、异常处理的语法3.1 try-

Android Mainline基础简介

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