First, let's take a look at the basic knowledge of the SAX Parser:
The Simple API for XML parser is an event-based parser. The event-driven streaming parsing method is from the beginning of the file to the end of the document, it cannot be paused or regressed. Its core is the event processing mode, which focuses on the event source and event processor. When an event is generated by the event source, an event can be processed by calling the corresponding processing method of the event processor. When the event source calls a specific method in the event processor, it also needs to pass the status information of the corresponding event to the event processor so that the event processor can determine its own behavior based on the provided event information.
The working principle of SAX: simply put, it refers to sequential scanning of documents. When a document is scanned, the elements start and end, and the document) the event handler function is notified when the event ends. The event handler function performs the corresponding action and continues the same scan until the document ends.
Next, let's take a small example to see how we use SAX to parse XML files in android:
(1) first, copy a beauties. xml file to the assets Directory. The content is as follows:
Fan Bingbing
28
Yang Mi
23
(2) create a layout file named saxtest. xml under layout. Its content is as follows:
(3) create a Beauty class corresponding to the nodes in xml in the src directory. The content is as follows:
Package com. saxtest; public class Beauty {private String name; private String age; public String getName () {return name;} public void setName (String name) {this. name = name;} public String getAge () {return age;} public void setAge (String age) {this. age = age ;}@ Overridepublic String toString () {return "Beauty info [age =" + age + ", name =" + name + "]" ;}}
Write another key class MySaxHandler. In this class, we generate the Beauty object from the parsed string and add it to the List. The Code has been commented out in detail. The content is as follows:
Package com. saxtest; import java. util. arrayList; import org. xml. sax. attributes; import org. xml. sax. SAXException; import org. xml. sax. helpers. defaultHandler; public class MySaxHandler extends DefaultHandler {// declare a Listprivate ArrayList loaded with the Beauty type
MList; // declare a Beauty type variable private Beauty beauty; // declare a String variable private String content; /*** MySaxHandler constructor ** @ param list loads the List object of the returned result */public MySaxHandler (ArrayList
List) {this. mList = list;}/*** the Method */@ Overridepublic void startDocument () throws SAXException {super. startDocument ();}/*** the Method */@ Overridepublic void endDocument () throws SAXException {super. endDocument ();}/*** when the SAX Parser parses a property value, the called Method * Where the parameter ch records the content of this attribute value */@ Overridepublic void characters (char [] ch, int start, int length) throws SAXException {super. characters (ch, start, length); content = new String (ch, start, length);}/*** when the SAX Parser resolves to an element, the method * in which the localName record is the element attribute name */@ Overridepublic void startElement (String uri, String localName, String qName, Attributes attributes) throws SAXException {super. startElement (uri, localName, qName, attributes); if ("beauty ". equals (localName) {beauty = new Beauty (); // create a Beauty object}/*** when the SAX Parser ends parsing an element, the method * in which the localName record is the element property name */@ Overridepublic void endElement (String uri, String localName, String qName) throws SAXException {super. endElement (uri, localName, qName); if ("name ". equals (localName) {beauty. setName (content);} else if ("age ". equals (localName) {beauty. setAge (content);} else if ("beauty ". equals (localName) {mList. add (beauty); // add the Beauty object to the List }}}
The third source file is SaxTestActivity. The layout file saxtest. xml of this Activity has been provided before. Now we paste the source code of the Activity, and the code has been commented out in detail:
Package com. saxtest; import java. io. inputStream; import java. util. arrayList; import javax. xml. parsers. SAXParser; import javax. xml. parsers. SAXParserFactory; import org. xml. sax. inputSource; import org. xml. sax. XMLReader; import android. app. activity; import android. content. res. assetManager; import android. OS. bundle; import android. widget. textView; import com. example. saxtest. r; public class SaxTestActivity extends Activity {// declare the Listprivate ArrayList for loading the Beauty object
BeautyList; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. saxtest); // initialize the beautyList linked list if (beautyList = null) {beautyList = new ArrayList
();} DoMyMission (); setupViews ();}/*** Method for parsing XML files using the SAX Parser */private void doMyMission () {try {// get the AssetManager manager object AssetManager as = this. getAssets (); // get beauties through the open method of AssetManager. the input stream InputStream of the xml file is =. open ("beauties. xml "); // obtain InputSource instance InputSource is2 = new InputSource (is) through the obtained InputStream; // use the factory method to initialize the SAXParserFactory variable spfSAXParserFactory spf = SAXParserFactory. newInstance (); // get the SAXParser instance SAXParser sp = spf through SAXParserFactory. newSAXParser (); // use SAXParser to obtain the XMLReader instance XMLReader xr = sp. getXMLReader (); // initialize the msh variable of the custom class MySaxHandler and pass beautyList to it to load data MySaxHandler msh = new MySaxHandler (beautyList ); // pass the object msh to xrxr. setContentHandler (msh); // call the parse method of xr to parse the input stream xr. parse (is2);} catch (Exception e) {e. printStackTrace () ;}}/*** Method for outputting the parsing result to the interface */private void setupViews () {String result = ""; for (Beauty B: beautyList) {result + = B. toString ();} TextView textView = (TextView) findViewById (R. id. textView); textView. setText (result );}}
Right-click the project code and the result is as follows:
Android-based SAX parsing XML