[Android] parses XML files using Sax

Source: Internet
Author: User
Tags xml parser

There are many ways to parse XML. You may be familiar with Dom parsing.

Dom (file object model) parsing: the parser reads the entire document and constructs a memory-resident tree structure. Then the code can operate on the tree structure based on the DOM interface.

Advantage: the entire document is read into the memory for easy operation: supports modification, deletion, reproduction, and other features.

Disadvantage: Read the entire document into the memory, leaving too many unnecessary nodes, wasting both memory and space.

Usage: Once a document is read, you need to perform operations on the document multiple times, and when the hardware resources are sufficient (memory, CPU ).

To solve the problem of Dom parsing, a sax parsing occurs. Features:

Advantage: you do not need to call the entire document and consume less resources. Especially in Embedded environments, such as Android, it is strongly recommended to use SAX parsing.

Disadvantage: Unlike Dom parsing, the document remains in the memory for a long time, and the data is not persistent. If no data is saved after the event, the data will be lost.

Usage: The machine has performance restrictions.

The event-driven mode is used to parse XML documents using sax. What is the event-driven model? It converts an XML document into a series of events, which are determined by the individual event processor.

The event-driven processing mode is mainly based on the event source and event processor (or listener. An object that can generate an event is called an event source, and an object that can respond to an event is called an event processor.

In the sax interface, the event source is xmlreader In the org. xml. Sax package. It parses the XML document through the parse () method and generates an event based on the document content. The event processor is the contenthandler, dtdhandler, errorhandler, and entityresolver interfaces in the org. xml. Sax package. They process different types of events generated by the event source during parsing (dtdhandler is used for parsing the document DTD ). The following table is detailed:

 

Among the above four interfaces, the most important is the contenthandler interface. The following describes the interface methods:

// Set a public void setdocumentlocator (locator Locator) Locator object that can locate the Event Location of the document content. // It is used to process the document parsing start event public void startdocument () throws saxexception // process the element start event. You can obtain the URI, element name, attribute class table, and other information of the namespace of the element from the parameter. Public void startelement (string namespacesuri, string localname, string QNAME, attributes ATTS) throws saxexception // process the element end event. You can obtain the URI Of The namespace where the element is located, public void endelement (string namespacesuri, string localname, string QNAME) throws saxexception // you can obtain the public void characters (char [] CH, int start, int length) throws saxexception from the parameters.

 

Here we will introduce the methods in xmlreader.

// Register and process the XML document parsing event contenthandlerpublic void setcontenthandler (contenthandler handler) // start parsing an XML document public void parse (inputsorce input) throws saxexception

To resolve an object, follow these steps:

Using sax in Android is traceable. You can easily find the tag in XML according to the following method and get the desired content. The specific implementation steps are as follows:

(1) Step 1: Create a factory class saxparserfactory. The Code is as follows:

SAXParserFactory factory = SAXParserFactory.newInstance();

(2) Step 2: Let the factory class generate a sax parsing class saxparser. The Code is as follows:

SAXParser parser = factory.newSAXParser();

(3) Step 3: Get An xmlreader instance from saxpsrser. The Code is as follows:

XMLReader reader = parser.getXMLReader();

(4) Step 4: register your handler to xmlreader. The most important thing is contenthandler. The Code is as follows:

RSSHandler handler = new RSSHandler();reader.setContentHandler(handler);

(5) Step 5: After an XML document or resource is converted into an inputstream stream that can be processed by Java, the parsing begins. The Code is as follows:

parser.parse(is);

In the above steps, the most important and key is step 4, Handler implementation.


The following is an XML file:

<?xml version="1.0" encoding="ISO-8859-1"?><resources><resource><id>0001</id><mp3.name>m1.mp3</mp3.name><mp3.size>5746816</mp3.size><lrc.name>m1.lrc</lrc.name><lrc.size>1778</lrc.size></resource><resource><id>0002</id>    <mp3.name>m2.mp3</mp3.name><mp3.size>5420198</mp3.size><lrc.name>m2.lrc</lrc.name><lrc.size>1598</lrc.size></resource></resources>

Add an object class so that we can put the parsed information into the object class, and then directly operate the object class.

Mp3info. Java

package android.model;public class Mp3Info {private String id;private String mp3Name;private String mp3Size;private String lrcName;private String lrcSize;public Mp3Info() {super();}public Mp3Info(String id, String mp3Name, String mp3Size, String lrcName,String lrcSize) {super();this.id = id;this.mp3Name = mp3Name;this.mp3Size = mp3Size;this.lrcName = lrcName;this.lrcSize = lrcSize;}@Overridepublic String toString() {return "Mp3Info [id=" + id + ", mp3Name=" + mp3Name + ", mp3Size="+ mp3Size + ", lrcName=" + lrcName + ", lrcSize=" + lrcSize+ "]";}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getMp3Name() {return mp3Name;}public void setMp3Name(String mp3Name) {this.mp3Name = mp3Name;}public String getMp3Size() {return mp3Size;}public void setMp3Size(String mp3Size) {this.mp3Size = mp3Size;}public String getLrcName() {return lrcName;}public void setLrcName(String lrcName) {this.lrcName = lrcName;}public String getLrcSize() {return lrcSize;}public void setLrcSize(String lrcSize) {this.lrcSize = lrcSize;}}

The following is the most important part. Create your own contenthandler. Check the following code:

Mp3listcontenthandler:

package android.xml;import java.util.List;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import android.model.Mp3Info;public class Mp3ListContentHandler extends DefaultHandler{private List<Mp3Info> infos=null;private Mp3Info mp3Info=null;private String tagName=null;public Mp3ListContentHandler(List<Mp3Info> infos) {super();this.infos = infos;}public List<Mp3Info> getInfos() {return infos;}public void setInfos(List<Mp3Info> infos) {this.infos = infos;}@Overridepublic void characters(char[] ch, int start, int length)throws SAXException {//System.out.println("-------characters------");String temp=new String(ch, start, length);if(tagName.equals("id")){mp3Info.setId(temp);}else if(tagName.equals("mp3.name")){mp3Info.setMp3Name(temp);}else if(tagName.equals("mp3.size")){mp3Info.setMp3Size(temp);}else if(tagName.equals("lrc.name")){mp3Info.setLrcName(temp);}else if(tagName.equals("lrc.size")){mp3Info.setLrcSize(temp);}}@Overridepublic void endDocument() throws SAXException {//System.out.println("------endDocument------");}@Overridepublic void endElement(String uri, String localName, String qName)throws SAXException {//System.out.println("---------endElement----------");if(qName.equals("resource")){infos.add(mp3Info);}tagName="";}@Overridepublic void startDocument() throws SAXException {// TODO Auto-generated method stubsuper.startDocument();//System.out.println("---------startDocument--------");}@Overridepublic void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {this.tagName=localName;//System.out.println("--------startElement-------");if(tagName.equals("resource")){mp3Info=new Mp3Info();}}}

To implement a contenthandler, perform the following steps:

1. Declare a class and inherit defaulthandler. Defaulthandler is a base class, which implements a contenthandler. We only need to rewrite the method.

2. Rewrite startdocument () and enddocument (). Generally, the initialization salary before the formal resolution is put in startdocument (), and the final work is put in enddocument.

3. Rewrite startelement (). When the XML Parser encounters a tag in the XML, it will call this function. In this function, we often use localname to determine and operate some data.

4. Rewrite the characters () method, which is a callback method. After the parser executes startelement (), the method is executed after the node content is parsed, And the CH [] parameter is the content of the node.

5. Rewrite the endelement () method. This method corresponds to startelement (). After parsing a tag node, execute this method. In another example, if an item is parsed, rssiiem will be added to rssfeed.

Finally, we implement an activity to display the parsing result:

Package android. test; import Java. io. stringreader; import Java. util. arraylist; import Java. util. iterator; import Java. util. list; import javax. XML. parsers. saxparserfactory; import Org. XML. sax. inputsource; import Org. XML. sax. xmlreader; import android. app. listactivity; import android. download. httpdownloader; import android. model. mp3info; import android. OS. bundle; import android. view. menu; import android. view. menuitem; import android. XML. mp3listcontenthandler; public class mp3listactivity extends listactivity {Private Static final int update = 1; Private Static final int about = 2;/** this method is called when you click the menu button, you can add your own control */@ overridepublic Boolean oncreateoptionsmenu (menu) {// todo auto-generated method stubmenu. add (0, update, 1, r.string1_list_update); menu. add (0, about, 2, r.string1_list_about); return Super. oncreateoptionsmenu (menu) ;}@ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main);} // processing button function. When you click the menu pop-up button, this function @ overridepublic Boolean onoptionsitemselected (menuitem item) is triggered) {// todo auto-generated method stub // system. out. println ("item ID ------>" + item. getitemid (); If (item. getitemid () = Update) {// the user clicks the update list button string xml = downloadxml ("http: // 172.23.10.234: 8080/MP3/resources. XML "); parse (XML);} else if (item. getitemid () = about) {// The user clicked the about Button} return Super. onoptionsitemselected (item);} Public String downloadxml (string urlstr) {httpdownloader = new httpdownloader (); string result = httpdownloader. download (urlstr); return result;} private list <mp3info> parse (string xmlstr) {saxparserfactory = saxparserfactory. newinstance (); List <mp3info> Infos = new arraylist <mp3info> (); try {// fixed XML file parsing syntax xmlreader = saxparserfactory. newsaxparser (). getxmlreader (); // set the content processor mp3listcontenthandler mp3listcontenthandler = new mp3listcontenthandler (Infos) for xmlreader; xmlreader. setcontenthandler (mp3listcontenthandler); // starts parsing the file xmlreader. parse (New inputsource (New stringreader (xmlstr); For (iterator = Infos. iterator (); iterator. hasnext ();) {mp3info mp3info = (mp3info) iterator. next (); system. out. println (mp3info) ;}} catch (exception e) {e. printstacktrace ();} return NULL ;}}

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.