How to parse xml files using SAX in Android Learning

Source: Internet
Author: User

Xml is often used on Android to transmit and exchange data. As an XML parser with high resolution speed and low memory usage, SAX (Simple API for xml) is very suitable for Android and other mobile devices. Event-driven SAX parsing determines whether the currently read characters comply with a part of the xml syntax and triggers the corresponding event. The nodes in xml are divided into two types: Element Node and Text Node ). For element nodes, the startElement event is triggered when the start tag is read, and the endElement event is triggered when the end tag is read. For a text node, the characters event is triggered when the text is read. In addition, the startDocument and endDocument events are triggered at the beginning and end of the xml document. Events are actually some callback methods defined in the ContentHandler interface, using SAX to parse an xml file is mainly to compile an implementation class that implements the ContentHandler Interface Based on the node and other information of the xml file.
 
The following will use SAX to parse the test. xml file and use AndroidTextCase to check whether the test result is correct.
The content of the text. xml file is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Persons>
<Person id = "23">
<Name> liming </name>
<Age> 30 </age>
</Person>
<Person id = "20">
<Name> lixiang </name>
<Age> 25 </age>
</Person>
</Persons>
The process is as follows:
Create an Android project xml01 in Eclipse
Create a text. xml file and put it under the src directory.
Create a JavaBean: Person with attributes such as id, name, and age.
Write a service class: SAXPersonService, parse the test. xml file, and write the internal class SAXParserHandler Based on the node name and other information in the test. xml file. The Code is as follows:
Package com. study. service;
Import java. io. InputStream;
Import java. util. ArrayList;
Import java. util. List;
Import javax. xml. parsers. SAXParser;
Import javax. xml. parsers. SAXParserFactory;
Import org. xml. sax. Attributes;
Import org. xml. sax. SAXException;
Import org. xml. sax. helpers. DefaultHandler;
Import com. study. bean. Person;
/**
* Parse the text. xml file using SAX
* @ Author Administrator
*
*/
Public class SAXPersonService {
Public List <Person> getPersons (InputStream inputStream) throws Throwable {
SAXParserFactory factory = SAXParserFactory. newInstance ();
SAXParser parser = factory. newSAXParser ();
SAXParserHandler handler = new SAXParserHandler ();
Parser. parse (inputStream, handler );
Return handler. getPersons ();
}
 
Private final class SAXParserHandler extends DefaultHandler {
 
Private List <Person> persons;
// Record the name of the previous accessed text node
Private String tag;
Private Person person;
 
Public List <Person> getPersons (){
Return persons;
}
@ Override
Public void characters (char [] ch, int start, int length)
Throws SAXException {
If (tag! = Null ){
If ("name". equals (tag )){
// Set name based on the value of the text node
Person. setName (new String (ch, start, length ));
} Else if ("age". equals (tag )){
// Set age based on the value of the text node
Person. setAge (Integer. parseInt (new String (ch, start, length )));
}
}
}
@ Override
Public void endElement (String uri, String localName, String qName)
Throws SAXException {
// LocalName is the tag name without the namespace prefix
If ("person". equals (localName )){
// Add the person object to the set
Persons. add (person );
// Set the person object to null
Person = null;
}

// When the node ends, you must set the tag to null.
// Otherwise, a blank character is assigned to the name and age, causing an error.
Tag = null;
}
@ Override
Public void startDocument () throws SAXException {
Persons = new ArrayList <Person> ();
}
@ Override
Public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// LocalName is the tag name without the namespace prefix
If ("person". equals (localName )){
Person = new Person ();
// Search for attribute values through Indexes
Person. setId (Integer. parseInt (attributes. getValue (0 )));
}

Tag = localName;
}
 
}
}
 
Add components required for Android testing to AndroidManifest. xml
<Uses-library android: name = "android. test. runner"/>
And
<Instrumentation android: name = "android. test. InstrumentationTestRunner"
Android: targetPackage = "com. study. action" android: label = "Tests for My App"/>
Write an AndroidTestCase: SAXPersonServiceTest. The test code is as follows:
Package com. study. action;
Import java. io. InputStream;
Import java. util. List;
Import android. test. AndroidTestCase;
Import android. util. Log;
Import com. study. bean. Person;
Import com. study. service. SAXPersonService;
Public class SAXPersonServiceTest extends AndroidTestCase {
Private static final String TAG = "SAXPersonServiceTest ";
Public void testGetPersons () throws Throwable {
SAXPersonService personService = new SAXPersonService ();
InputStream inputStream = this. getClass (). getClassLoader (). getResourceAsStream ("test. xml ");
List <Person> persons = personService. getPersons (inputStream );
For (Person person: persons ){
Log. I (TAG, person. getId () + "," + person. getName () + "," + person. getAge ());
}
}
}
Enter the log and the running result is as follows:

Author: "new departure"

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.