📄 sax.xtp
字号:
<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"><top> <a/> <b> <b1/> <b2/> </b> <c/></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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -