Introduction
The Pull parser is built-in to the Android system. The Pull parser is similar to the SAX parser. It provides similar events, such as the start element and the event introducing element. Using () can enter the next element and trigger the corresponding event, and then perform corresponding processing. When the element starts parsing, the () method can be called to obtain the value of the next Text type element.
Features
(1) Simple structure, one interface, one other, and one factory form a Pull parser
(2) Simple and easy to use. The Pull parser has only one important method next(). It is used to retrieve the next event, and there are only five events, START_DOCUMENT, START_TAG ,TEXT, END_TAG, END_DOCUMENT
(3) Minimum memory consumption. Pull parser is the same as SAX parser. It uses less memory temporarily, but SAX parsing is a bit cumbersome, and the DOM consumes memory, so Pull is recommended to use
structure
The project package is named , and the file exists in the root directory of src
-- -- -- -- -- -- -- -- -- -- -- -- --
4. Example Pull parses XML
Create a new one in the src directory first
<?xml version="1.0" encoding="UTF-8"?> <persons> <person > <name>xiaanming</name> <age>23</age> </person> <person > <name>liudehua</name> <age>28</age> </person> </persons>
Create a new PullXMLService
package .pull_parser; import ; import ; import ; import .; import ; import ; public class PullXMLService { public static List<Person> readXML() throws Exception{ //Get the input stream of the file below the src directory InputStream is = ().getResourceAsStream(""); // Used to store parsed Person objects List<Person> persons = null; //A tag boolean flag = false; Person person = null; //Instantiate an XmlPullParser object XmlPullParser parser = (); //Set the input stream and encoding (is, "UTF-8"); //The first event was triggered, and according to the syntax of XML, that is, it starts to understand the document from him int eventCode = (); //If the obtained event code is the end of the document, then the parsing ends while (eventCode != XmlPullParser.END_DOCUMENT) { switch(eventCode){ case XmlPullParser.START_DOCUMENT:{ // When we start parsing, we usually do some initialization operations persons = new ArrayList<Person>(); break; } case XmlPullParser.START_TAG:{ //Judge whether the current element is the element that needs to be retrieved if("person".equals(())){ flag = true; person = new Person(); (((0))); } if(flag){ if("name".equals(())){ (()); }else if("age".equals(())){ ((())); } } break; } case XmlPullParser.END_TAG:{ if("person".equals(()) && person != null){ flag = false; (person); ("log", ()); person = null; } break; } } //This step is very important. This method returns an event code, which is also the method to trigger the next event eventCode = (); } return persons; } }