This article describes the sample code for reading XML files using the SAX method. it has some reference value. let's take a look at the XML file.
Song of Ice and Fire
George Martin
2014
89
Andersen fairy tale
2004
77
English
Handler. java class
Package xmltes; import javax. xml. stream. events. characters; import javax. xml. stream. events. startElement; import org. xml. sax. attributes; import org. xml. sax. SAXException; import org. xml. sax. helpers. defaultHandler; public class handler extends DefaultHandler {private static int bookNum = 0; // traverse the start tag of the xml file @ Override public void startElement (String uri, String localName, String qName, attributes attributes) throws SAXException {// call the startElement method super of the DefaultHandler parent class. startElement (uri, localName, qName, attributes); // identify whether a tag has an attribute, such as book if (qName. equals ("book") {bookNum ++; System. out. println ("============================== start to traverse the content of the" + bookNum + "book ======== ========== "); // start parsing the attribute name of the book element. // you can determine the attribute name based on the name./* String value = attributes. getValue ("id"); System. out. println ("the attribute value of the book is" + value); * // If you do not know the attribute name of the number, int num = attributes. getLength (); for (int I = 0; I
Test class
Package xmltes; import java. io. IOException; import javax. xml. parsers. parserConfigurationException; import javax. xml. parsers. SAXParser; import javax. xml. parsers. SAXParserFactory; import org. xml. sax. SAXException; public class SAXTest {public static void main (String [] args) {try {// Get the SAXParserFactory instance SAXParserFactory = SAXParserFactory. newInstance (); // get SAXParser instance SAXParser parser = factory through factory. newSAXParser (); // Create a SAXParserHandler object handler = new handler (); parser. parse ("001.xml", handler);} catch (ParserConfigurationException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (SAXException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}
The above is the detailed content of the sample code read by the XML file using the SAX method. For more information, see other related articles in the first PHP community!