Android three ways to parse XML sax, Pull, dom_android

Source: Internet
Author: User
Tags stub tagname

In Android development, often used to parse XML files, the common way to parse XML is three kinds: SAX, Pull, Dom parsing method. Recently made an Android version of the CSDN reader, using two of these (sax,pull), this article on the Android parsing XML three ways to make a summary.

The XML sample parsed today (Channels.xml) is as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<channel>
<item id= "0" url= "http://www.baidu.com" > Baidu </item>
<item id= "1" url= "http://www.qq.com" > Tencent </item>
<item id= "2" url= "http:/ /www.sina.com.cn "> Sina </item>
<item id=" 3 "url=" http://www.taobao.com "> Taobao </item>
< /channel> 

First, use Sax to parse

Basic knowledge:

This method of parsing is an event-based API that has two parts, parsers and event handlers, the parser is the XmlReader interface, is responsible for reading XML documents, and sending events to the event handler (also event source), event handler ContentHandler interface, Responsible for responding to the events sent and processing XML documents.

The following are common methods for ContentHandler interfaces

public abstract void characters (char[] ch, int start, int length)

This method to receive the character block notification, this method is used by the parser to report character data blocks, which, in order to improve the efficiency of parsing, place all the strings read into a character array (CH) as parameters passed to the character method, if you want to get the character data read in this event, You need to use the start and length properties.

public abstract void Startdocument () receive notification of document start

public abstract void Enddocument () Notification of receiving end of document

public abstract void Startelement (String uri, String localname, String qName, Attributes Atts) receives the label from the beginning of the document

public abstract void EndElement (String uri, String localname, String qName) a label that receives the end of a document

In general use in order to simplify development, in Org.xml.sax.helpers provides a DefaultHandler class, it implements the ContentHandler method, we just want to inherit DefaultHandler method.

In addition, the SAX parser provides a factory class: The Saxparserfactory,sax parsing class is parsed by the parser method that SAXParser can call it.

   Read some basics and start coding (core code, download code in attachment)

public class Saxpraserhelper extends DefaultHandler {final int ITEM = 0x0005;
 List<channel> list;
 Channel Chann;

 int currentstate = 0;
 Public list<channel> GetList () {return List; * * * Interface character block notification * * @Override public void characters (char[] ch, int start, int length) throws Saxexception {//T
  Odo auto-generated Method Stub//super.characters (CH, start, length);
  String thestring = string.valueof (ch, start, length);
   if (currentstate!= 0) {chann.setname (thestring);
  CurrentState = 0;
 } return;
  * * * Receive document end notification/@Override public void Enddocument () throws Saxexception {//TODO auto-generated stub
 Super.enddocument (); * * * receive TAG end notification/* @Override public void endelement (string uri, String localname, String qName) throws Saxexcepti
 on {//TODO auto-generated Method stub if (Localname.equals ("item")) List.add (Chann); * * * Document START Notification * * @Override public void startdocument () throws Saxexception {//TODO auto-generated method Stub list = new Arraylist<channel> (); * * * label start notification/@Override public void startelement (string uri, String localname, String qName, Attributes attrib
  Utes) throws Saxexception {//TODO auto-generated method Stub Chann = new channel (); if (Localname.equals ("item")) {for (int i = 0; i < attributes.getlength (); i++) {if attributes.getlocalname (i
    ). Equals ("id")) {Chann.setid (Attributes.getvalue (i));
    else if (attributes.getlocalname (i). Equals ("url")) {Chann.seturl (Attributes.getvalue (i));
   } currentstate = ITEM;
  Return
  } currentstate = 0;
 Return

 }
}
Private List<channel> Getchannellist () throws Parserconfigurationexception, Saxexception, IOException
 {
  //instantiation of a SAXParserFactory object
  SAXParserFactory factory=saxparserfactory.newinstance ();
  SAXParser parser;
  Instantiate SAXParser object, create XmlReader object, Parser
  parser=factory.newsaxparser ();
  XMLReader Xmlreader=parser.getxmlreader ();
  Instantiate handler, event handler
  saxpraserhelper helperhandler=new saxpraserhelper ();
  Parser Registration Event
  Xmlreader.setcontenthandler (Helperhandler);
  Read the file stream
  InputStream stream=getresources (). Openrawresource (r.raw.channels);
  InputSource is=new InputSource (stream);
  Parse file
  xmlreader.parse (is);
  return Helperhandler.getlist ();
 }

From the second part of the code, you can see the steps to parse XML using sax:

1, the instantiation of a factory saxparserfactory

2. Instantiate the Saxpraser object and create the XmlReader parser

3. Instantiate handler, processor

4, the parser registers an event

4. Read file stream

5. Parse File

Second, the use of Pull mode analysis

Basic knowledge:

In the Android system, many of the resource files are in XML format, and the way to parse the XML in the Android system is to parse it using the PUL parser, which is the same as Sax parsing (personal feeling is simpler than sax), and is also resolved using event-driven When the pull parser starts parsing, we can call its next () method to get the next parsing event (that is, the start document, the end document, the start tag, the end tag), and the Xmlpullparser Getattributte () can be invoked when an element is in it. method to get the value of the property, or call its nexttext () to get the value of this node.

In fact, the above description is a description of the entire analytic process, look at the code

Private list<map<string, string>> GetData () {list<map<string, string>> List = new Arraylist&lt ;
  Map<string, string>> ();

  Xmlresourceparser XRP = Getresources (). GETXML (R.xml.channels); try {//until the end of the document while (Xrp.geteventtype ()!= xmlresourceparser.end_document) {//If you encounter a start tag if (Xrp.geteve  Nttype () = = Xmlresourceparser.start_tag) {String tagName = Xrp.getname ();//Get the name of the label if (Tagname.equals ("item"))
      {map<string, string> Map = new hashmap<string, string> ();
      String id = xrp.getattributevalue (NULL, "id");//Get Property value Map.put ("id", ID) by property name;
      String url = xrp.getattributevalue (1);//Get Property value map.put ("url", URL) through property index;
      Map.put ("Name", Xrp.nexttext ());
     List.add (map); } xrp.next ()//Get resolve next event} catch (Xmlpullparserexception e) {//TODO auto-generated catch block E
  . Printstacktrace ();
  catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
 } return list;


 }

Third, using Dom method to parse

Basic knowledge:

Finally, look at the DOM parsing method, this method of parsing itself has not been used before (in Java EE development is more common, did not do this), in the process of Dom parsing, is to first read all the DOM file into memory, and then use the DOM API to traverse all the data, retrieve the desired data, This approach is obviously a way of comparing memory consumption, for mobile devices such as mobile phones, memory is very limited, so for the larger XML file, this is not recommended, but the DOM has its advantages, it is more intuitive, in some ways than sax way simpler. You can also consider using DOM when the XML document is relatively small.

The core code for DOM parsing is as follows:

public static list<channel> getchannellist (InputStream stream) {list<channel> list=new Arraylist<chann
  
  El> (); Gets the Documentbuilderfactory object that the object can get Documentbuilder object Documentbuilderfactory factory=
  
  Documentbuilderfactory.newinstance ();
   try {//Get Documentbuilder Object Documentbuilder builder=factory.newdocumentbuilder ();
   Gets the Document object document Document=builder.parse (stream) representing the entire XML;
   Get "root node" Element root=document.getdocumentelement (); 
   Gets the node for all items of the root node nodelist items=root.getelementsbytagname ("item");
    Iterate over all nodes for (int i=0;i<items.getlength (); i++) {Channel chann=new channel ();
    Element item= (Element) Items.item (i);
    Chann.setid (Item.getattribute ("id"));
    Chann.seturl (item.getattribute ("url"));
    Chann.setname (Item.getfirstchild (). Getnodevalue ());
   List.add (Chann);
  The 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 ();
 } return list;
 }

Summarize the steps of Dom parsing (similar to sax)

1, call the Documentbuilderfactory.newinstance () method to get the DOM parser factory class instance.

2, call the parser factory instance Class Newdocumentbuilder () method to get the DOM parser object

3. The parse () method that invokes the DOM parser object parses the XML document and gets the document object representing the entire file.

Iv. Summary

In addition to the above three kinds of ways to parse XML, such as DOM4J, Jdom, and so on. But there are two basic parsing methods, one is event-driven (on behalf of Sax) and the other is based on the document structure (representing the DOM). The other is just a different grammar.

SOURCE Download: Android parsing xml

Original address: http://www.cnblogs.com/JerryWang1991

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.