`

Simple API for XML(SAX)详解与实例

阅读更多

What is SAX

SAX 是一个 event-driven serial-access 型的 XML 处理机制。

event-driven SAX 提供 面向 elements, text comments 不同 事件的处理 方法,当解析器 XML 数据 就会 些方法。

serial-access SAX 工作起来有点像一个 连续 I/O 流,能 实时 送和接收数据,它不会去构造 XML 构,所以只需要很少的内存。当然 在另一方面 致了你不能退回到早前 取的一个 element 或者跳到后面 到的 element

When To Use SAX

SAX XML 文件的最快的,内存需求最小的 解析器 ,所以当你只需要 简单 读取 数据,好 你的程序运行 些数据的 时候 ,SAX 是很好的 选择 。因此, SAX 常被用于 servlet 和面向 网络 编程的存取 XML 文件。

 

The SAX Packages

SAX 解析器存在与 JDK 如下的包中:

org.xml.sax:the SAX interfaces
org.xml.sax.ext : SAX extensions
org.xml.sax.helpers : helper classes
javax.xml.parsers : the SAXParserFactory class

 

SAX API 概述

附件2是 SAX API 的略图。

 

SAX 解析器包含了一个 SAXReader 实例,当解析器的 parse 方法被调用时, reader 会调用对不同事件的处理方法 ( event-driven )

这些方法在以下四种 handler 中被定义。用户可以在自定义的解析器中重写这些方法。

- org.xml.sax.ContentHandler : Receive notification of the logical content of a document.
- org.xml.sax.EntityResolver : Basic interface for resolving entities.
- org.xml.sax.DTDHandler : Receive notification of basic DTD-related events.
- org.xml.sax.ErrorHandler : Basic interface for SAX error handlers.

 

DefaultHandler :适配了上面的四个接口,可用于不同事件的处理

自定义 SAX 解析器

以下是自定义一个SAX解析器的详细方法:

1.继承DefaultHandler

   因为DefaultHandler同时实现了EntityResolver,DTDHandler,ContentHandler和ErrorHandler四个接口,
   这样你就可以在你的XML解析器中调用或重写这四个接口中定义的面向不同事件的处理方法。

2.创建简单的parser(Validating parser)

  创建一个parser,并使用Schema或DTD对XML文件进行校验

 // Use an instance of ourselves as the SAX event handler
  DefaultHandler handler = new MyHandler();
  // Use the validating parser
  SAXParserFactory factory = SAXParserFactory.newInstance();
  factory.setValidating(true);
  try {
      // Parse the input
      SAXParser saxParser = factory.newSAXParser();
      saxParser.parse( new File("XXX"), handler );
  } catch (Throwable t) {
      t.printStackTrace();
  }

3.ContentHandler

  1)处理Document 事件的method

     - startDocument:  开始解析XML文件,此方法只会被调用一次
     - endDocument:  解析XML文件结束

  2)处理Element 事件的method

     - startElement:  开始解析XML文件的一个元素,在此方法中,可以获得该元素的属性和其对应的value值
     - endElement:  解析该元素完毕

  3)处理Character 事件的method

     - characters:  用于解析元素中的字符数据
     注:当XML文档中没有使用DTD进行校验时,当遇到whitespace时,该方法也会被调用。

例:
<element1 att1="value1">        ---Element 事件
        These are characters.        ---Character 事件
</element1>                              ---Element 事件

    4)其他method

     - setDocumentLocator:  该方法只在解析开始前被调用一次。用户可获得当前所解析的XML文件的位置和public

           identifier等信息。

     - ignorableWhitespace:  使用DTD校验时,通过重写此方法,用户可以查看XML中哪些地方存在whitespace
     - processingInstruction:  通过此方法可以获得XML中定义的命令(target)和命令所处理的内容(data)

例:
<?my.presentation.Program QUERY="exec, tech, all"?>

target: my.presentation.Program
data: QUERY="exec, tech, all"

 

4.ErrorHandler

  解析XML时发生的异常包括三种:a fatal error, an error, and a warning.
  -fatalError(SAXParseException):  用于处理致命error
  -error(SAXParseException):  用于处理非致命error,发生于对XML进行校验时。默认是被忽略的。由于当一个XML

       发生校验错误时,用户可能不希望再解析下去了,此时,可以将此类异常自定义为致命error抛出。

  -warning(SAXParseException):  用于处理警告。默认是被忽略的。用户可以通过自定义的方式打印出异常具体

       的发生地点和信息。

5.DTDHandler

  事件处理method
  -notationDecl:  Receive notification of a notation declaration event.
  -unparsedEntityDecl:  Receive notification of an unparsed entity declaration event.

6.EntityResolver

  事件处理method
  -resolveEntity:  该方法用于将public ID (URN)装换为system ID (URL),返回一个InputSource object。

7.LexicalHandler

  SAX中使用org.xml.sax.ext.LexicalHandler来处理comments, CDATA sections和references。

  1)实现LexicalHandler接口

  2)创建一个parser

    // Use an instance of ourselves as the SAX event handler
    DefaultHandler handler = new MyHandler();

   // Use the validating parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
   
    try {
          // Parse the input
          SAXParser saxParser = factory.newSAXParser();
          XMLReader xmlReader = saxParser.getXMLReader();
          xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler",handler);
          saxParser.parse( new File("XXX"), handler );
     } catch (Throwable t) {
          t.printStackTrace();
     }

    3)事件处理method

    -comment(String comment):  解析XML文件中的注释
    -startCDATA(), endCDATA():  Tells when a CDATA section is starting and ending, which tells your

        application what kind of characters to expect the next time characters()is called
    -startEntity(String name), endEntity(String name):  Gives the name of a parsed entity
    -startDTD(String name, String publicId, String systemId), endDTD():  Tells when a DTD is being 

         processed, and identifies it

SAX Sample

附件1(我将官网上的sample进行整合,基本上囊括了上述所有的知识点)用于解析一个XML文件,并将其详细信息(片段如下)打印出来。

输出片段:
COMMENT: SUBSTITUTIONS WORK IN ATTRIBUTES, TOO
ELEMENT: <slideshow
ATTR: title "WonderWidget Slide Show"
ATTR: date "Date of publication"
ATTR: author "Yours Truly"
>
IGNORABLE
COMMENT: PROCESSING INSTRUCTION
IGNORABLE
 

 

  • 大小: 37.4 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics