XML parsing-pull parsing in Android

Source: Internet
Author: User

With two XML parsing DOM and Sax methods in front, Dom is a more logical way of thinking, and Sax event-driven focus on efficiency, in addition to these two ways, you can use the Android built-in pull parser to parse XML files. The pull parser works like a SAX parser and is also triggered by events. Pull parsing gives the application full control over how the document should be parsed, such as the start and end element events, using Parser.next () to enter the next element and trigger the event. By using the Parser.geteventtype () method to get the code value of the event, parsing is done at the beginning with most of the processing. Events are sent as numeric codes, so you can use a switch to handle events of interest, and only pull-mode read XML callback methods return numbers.

Pull Create XML

create XML first instantiates a serialized object, followed by tag:

public void Createxml () {//Initialize a serialized object XmlSerializer serializer = Xml.newserializer (); File path = new file (Getfilesdir (), "Booktest.xml"), try {fileoutputstream fostream = new FileOutputStream (path); Serializer.setoutput (Fostream, "utf-8");//Set document <?xml version= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '?> Serializer.startdocument ("Utf-8", true);//Set root node Serializer.starttag (null, "Books"); for (int i = 1; i < 4; i++) {//Set child nodes 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 ();} catch (FileNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch ( IllegalArgumentException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (IllegalStateException e) {// TODO auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//TODO Auto-genErated catch Blocke.printstacktrace ();}} 

Results of the generated XML:

<?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 Read XML

Take a look at the first one:

Display content Call getlistbooksbypull method:

Public list<book> Getlistbooksbypull () {List = new arraylist<book> (); File path = new file (Getfilesdir (), "Booktest.xml"), try {fileinputstream inputstream = new FileInputStream (path);//Get Pul L Parser Object Xmlpullparser parser = Xml.newpullparser ();//Specify parsed file and encoding format parser.setinput (InputStream, "utf-8"); int eventtype = Parser.geteventtype ();  Get event type Book 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 ();//re-assign, otherwise it will die loop} catch (FileNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (Xmlpullparserexception e) {//TODO auto-generatedCatch Blocke.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return list;}

Pull is simple and easy to read relative to Dom and sax, but it's a simple summary of several common methods: read the declaration of XML to return start_document; Reads the end of XML to return end_document; Reads the start tag of the XML return Start_tag, reads the end tag of the XML return End_tag reads the text back into the XML return text.

When the activity is loaded, call:

listview ListView = (listview) Findviewbyid (R.id.list_pull); arraylist

A brief review of three parsing methods, DOM parsing XML is to first read the XML document into memory, and then use the DOM API to access the tree structure, and get the data. This is easy to write, but it consumes memory. If the data is too large, the phone configuration will not be able to panic. Sax Parsing is a sequential scan of a document that notifies the event handler when a document is scanned to the beginning and end of an element (elements), the end of the document, and so on, and the event handler functions as a corresponding action. Then continue the same scan until the end of the document. The pull parser is similar to the SAX parser, but the SAX parser works by automatically pushing events into the registered event handler, so you can't control the active end of the event; The pull parser works by allowing your application code to proactively get events from the parser, because it is an active fetch event, so you can no longer get the event after the desired condition has been met, ending the resolution. Pull's writing is really light and easy to get started, and individuals prefer pull.

XML parsing-pull parsing in Android

Related Article

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.