sax.xtp

来自「解压在c盘」· XTP 代码 · 共 86 行

XTP
86
字号
<s1 title="SAX Parsing"><p>SAX parsers use a callback mechanism to parse XML.  Applicationsregister a <var/ContentHandler/> to receive the parsing events.  Althoughthis is a little more complicated, it's more efficient because there'sno need to build any data structures.</p><p>Because Sun's JAXP API only supports SAX 1.0, the following exampleinstantiates the Resin parser directly.  Of course, if you want to parseHTML with a SAX API, you'll need to instantiate <var/Html/> instead.</p><p>The following example just prints the element names, properly indented,as they're parsed.</p><example title="Input File">&lt;top>  &lt;a/>  &lt;b>    &lt;b1/>    &lt;b2/>  &lt;/b>  &lt;c/>&lt;/top></example><p><var/DefaultHandler/> is a convenient abstract implementation of theSAX handler APIs.  By extending <var/DefaultHandler/>, you can justimplement the methods your application needs.</p><p>The SAX parser will call <var/startElement()/> when it finishesparsing the open tag.  In this case, I'm ignoring the namespace junkand just using the tag name, <var/qName/>.</p><p>The <var/endElement()/> callback just decrements the depth to getthe correct value.</p><example title="SAX Handler Class">import java.io.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import com.caucho.xml.*;public class MyHandler extends DefaultHandler {  int depth;  public void startElement(String namespaceURI, String localName,                           String qName, Attributes atts)  {    for (int i = 0; i < depth; i++)      System.out.print(" ");    System.out.println(qName);    depth += 2;  }  public void endElement(String namespaceURI, String localName,                         String qName)  {    depth -= 2;  }}</example><p>To parse with SAX, you must register your handlerusing <var/setContentHandler/>.</p><example title="Parsing using SAX">// Create a new parserXml xml = new Xml();xml.setContentHandler(new MyHandler());xml.parse("test.xml");</example><p>And the result looks like:</p><results>top  a  b    b1    b2  c</results></s1>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?