This article describes the XML parsing of the sax parsing case (1) Read the contact. xml file, complete output of the document content details, if necessary, refer to the next, create a Demo2 class:
Import java. io. file; import javax. xml. parsers. SAXParser; import javax. xml. parsers. SAXParserFactory;/*** read contact. xml file, complete output file content * @ author APPle **/public class Demo2 {public static void main (String [] args) throws Exception {// 1. create SAXParserSAXParser parser = SAXParserFactory. newInstance (). newSAXParser (); // 2. read the xml file MyDefaultHandler2 handler = new MyDefaultHandler2 (); parser. parse (new File (". /src/contact. xml "), handler); String content = handler. getContent (); System. out. println (content );}}
2. create a custom mydefaulthand2
Import org. xml. sax. attributes; import org. xml. sax. SAXException; import org. xml. sax. helpers. defaultHandler;/*** SAX processor program * @ author APPle */public class MyDefaultHandler2 extends DefaultHandler {// store xml document information private StringBuffer sb = new StringBuffer (); // get xml information public String getContent () {return sb. toString ();}/*** start tag */@ Overridepublic void startElement (String uri, String localName, String qName, Attri Butes attributes) throws SAXException {sb. append ("<" + qName); // you can determine whether the attribute if (attributes! = Null) {for (int I = 0; I ") ;}/ *** text content */@ Overridepublic void characters (char [] ch, int start, int length) throws SAXException {// Get the currently read text String content = new String (ch, start, length); sb. append (content);}/*** end tag */@ Overridepublic void endElement (String uri, String localName, String qName) throws SAXException {sb. append ("
");}}
Print the output result:
Zhang San
20
134222223333
Zhangsan@qq.com
432221111
Eric
20
134222225555
Lisi@qq.com
432222222
The above is the case of the sax parsing of XML parsing (1) Read the contact. xml file and completely output the content of the document. For more information, see The PHP Chinese website (www.php1.cn )!