XML parsing in Android-PULL Parsing

Source: Internet
Author: User

XML parsing in Android-PULL Parsing
I have previously written two XML-based Dom and SAX parsing methods. Dom is more in line with the way of thinking. The SAX event-driven pay attention to efficiency, in addition to these two methods, you can also use the Android built-in Pull parser to parse XML files. The Running Method of the Pull parser is similar to that of the SAX Parser and event-triggered. The Pull parsing method allows the application to completely control how the document is parsed, such as starting and ending element events. You can use parser. next () to enter the next element and trigger the corresponding event. The Parser. getEventType () method is used to obtain the code value of the event. parsing completes most of the processing at the beginning. The event is sent as a numeric code. Therefore, you can use a switch to process the event you are interested in. The returned number is returned only when you read the xml callback method in the PULL mode. Pull create XML instantiate a serialization object first, and then operate through the Tag: public void createXML () {// initialize a serialization object XmlSerializer serializer = Xml. newSerializer (); File path = new File (getFilesDir (), "BookTest. xml "); try {FileOutputStream foStream = new FileOutputStream (path); serializer. setOutput (foStream, "UTF-8"); // configuration document <? Xml version = '1. 0' encoding = 'utf-8' standalone = 'Yes'?> Serializer. startDocument ("UTF-8", true); // sets the root node serializer. startTag (null, "Books"); for (int I = 1; I <4; I ++) {// sets the subnode serializer. startTag (null, "Book"); serializer. attribute (null, "name", "books" + I); serializer. startTag (null, "Title"); serializer. text ("content" + I); serializer. endTag (null, "Title"); serializer. endTag (null, "Book");} serializer. endTag (null, "Books"); serializer. endDocument ();} ca Tch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IllegalArgumentException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IllegalStateException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} generated XML result: <? Xml version = '1. 0' encoding = 'utf-8' standalone = 'Yes'?> <Books> <Book name = "Book 1"> <Title> content 1 </Title> </Book> <Book name = "Book 2"> <Title> content 2 </Title> </Book> <Book name = "Book 3"> <Title> content 3 </Title> </Book> </Books> Pull calls getListBooksByPull to read XML display content method: public List <Book> getListBooksByPull () {list = new ArrayList <Book> (); File path = new File (getFilesDir (), "BookTest. xml "); try {FileInputStream inputStream = new FileInputStream (path); // obtain the pull parser object XmlP UllParser parser = Xml. newPullParser (); // specify the parsed file and encoding format parser. setInput (inputStream, "UTF-8"); int eventType = parser. getEventType (); // obtain the event type Book = null; while (eventType! = XmlPullParser. END_DOCUMENT) {String tagNameString = parser. getName (); switch (eventType) {case XmlPullParser. START_TAG: if ("Book ". equals (tagNameString) {// Book tag book = new Book (); book. setName (parser. getAttributeValue (null, "name");} else if ("Title ". equals (tagNameString) {// Title Tag book. setTitle (parser. nextText ();} break; case XmlPullParser. END_TAG: if ("Book ". equals (tagNameString )){ List. add (book) ;}break; default: break;} eventType = parser. next (); // assign a value again, otherwise it will have an endless loop} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (XmlPullParserException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();} return list;} compared with Dom and SAX, Pull is relatively simple and easy to read. The following common methods are as follows: START_DOCUMENT is returned when the declaration of the read xml is returned; END_DOCUMENT is returned when the xml is read; START_TAG is returned when the start tag of the read xml is returned, return the END_TAG to read the xml TEXT and return the TEXT. called when the Activity is loaded: ListView listView = (ListView) findViewById (R. id. list_pull); ArrayList <HashMap <String, String> arrayList = new ArrayList <HashMap <String, String> (); list = getListBooksByPull (); for (Book book: list) {HashMap <String, String> map = new HashMap <String, String> (); map. put ("itemTitle", book. getName (); map. put ("itemText", book. getTitle (); arrayList. add (map);} SimpleAdapter simpleAdapter = new SimpleAdapter (this, arrayList, R. layout. book, new String [] {"itemTitle", "itemText"}, new int [] {R. id. itemTitle, R. id. itemText}); listView. setAdapter (simpleAdapter); a brief review of the three parsing methods. Dom parses xml by first reading all xml documents into the memory, and then uses DOM APIs to access the tree structure and obtain data. This is easy to write, but it consumes a lot of memory. If the data is too large, the phone configuration may fail. SAX resolution refers to the sequential scanning of documents. It notifies event processing functions when scanning documents, such as starting and ending, elements, and documents, the event processing function performs the corresponding action, and then continues the same scan until the end of the document. The Pull parser is similar to the SAX Parser, but the SAX Parser automatically pushes events to the registered event processor for processing. Therefore, you cannot control the event processing to automatically end; the Pull parser is used to allow your application code to actively retrieve events from the parser, because it is actively obtaining events, therefore, after meeting the required conditions, you can stop obtaining the event and complete the parsing. Pull is simple and easy to use. I personally prefer Pull.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.