[XML learning notes] [3.1] use sax through JAXP

xiaoxiao2021-03-06  42

In the previous notes, we have mentioned two distinct ways to read XML data, SAX is one of them. Look at a code:

/ ** /

/ * * CREATED ON 2005-2-24 * All rights reserved. * * /

package sean.home.test; import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; Import org.xml.sax.helpers.defaulthandler;

/ ** /

/ ** * @Author sean gao *

* gaoyuxiang@gmail.com * * * /

public

Class

Main

{Public static void main (String [] args) throws Exception {SAXParserFactory factory = SAXParserFactory.newInstance (); SAXParser parser = factory.newSAXParser (); DefaultHandler myHandler = new DefaultHandler () {public void startDocument () throws SAXException {System. out.println ( "XML document starts");} public void endDocument () throws SAXException {System.out.println ( "XML document ends");} public void startElement (String uri, String localName, String qualifiedName, Attributes attributes) throws SAXException {System.out.println ( "element" qualifiedName "starts");} public void endElement (String uri, String localName, String qualifiedName) throws SAXException {System.out.println ( "element" qualifiedName " Ends ");} public void charact ERS (Char [] CH, INT Start, Int Length {System.Out.Println (New String (ch, start, length));}}; Parser.Parse (New File), MyHandler; }}} In this code, we get a Parser through SaXParserFactory, then customize an event that triggered when SAX reads the XML file, such as startDocument means that the end of the element, and character in the element. Read content, etc. Here I am written directly into anonymous internal classes, Exception does not do anything, which is usually unreasonable in practice.

Basically SAX's implementation and use is straightforward, it is to deal with one event.

转载请注明原文地址:https://www.9cbs.com/read-53972.html

New Post(0)