Android Development (I) Analysis of XML file parsing in the SAX Mode

Source: Internet
Author: User
Tags xml parser

SAX parsing XML:
Basic Principles of SAX:
The event-driven parsing of XML files is performed row-by-row in streaming mode. It does not need to parse the entire document and parse the document in order of content, SAX checks whether the currently mentioned characters are valid for a part of the XML syntax. If they match, it triggers events (such as startDocument (), endDocument (), and so on ), it does not record the labels encountered previously, and it is an XML parser with fast parsing speed and low memory usage,
Procedure for parsing SAX:
1. Create a new instance from SAXPraserFactory
2. Get a new SAX Parser object SAXParser from SAXParserFactory.
3. Call the. parse () method of the SAXParser object with two parameters: the input stream and the DefaultHandler object. DefaultHandler implements the ContentHandler interface. The ContentHandler interface defines a series of method events, such:

Public abstract void startDocument ()

Method: this event is triggered by parsing a document.

Public abstract void endDocument ()

Method: this event is triggered when File Parsing ends.

Public abstract void startElement (String uri, String localName, String qName, Attributes atts)

Method: this event is triggered when an element is read.
Parameter description:
Uri: namespace
LocalName: name of the tag without the namespace prefix
QName: the name of the tag with the specified namespace prefix.
Atts: obtain all attributes and corresponding values.

Public abstract void endElement (String uri, String localName, String qName)

Method: this event is triggered when the read Tag ends. The parameters are described as follows:

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

Method: used to process content read in an XML file.
Parameter description:
Ch: used to store the File Content
Start: start position of the read string in this array
Length: length
We can use new String (ch, start, length) to obtain the content.
 
The following uses the person. xml file as an example to simulate parsing this XML file using the SAX Parser:

<? Xml version = "1.0" encoding = "UTF-8"?>
 
<Persons>
 
<Person id = "23">
 
<Name> Li Ming </name>
 
<Age> 30 </age>
 
</Person>
 
<Person id = "20">
 
<Name> Li xiangmei </name>
 
<Age> 25 </age>
 
</Person>
 
</Persons>

 
The event triggered by parsing person. xml is:

Read tags and content Trigger event
{Document start} StartDocument ()
<Persons> StartElement (, "persons", null, "{Attributes }")
"\ N \ t" Characters ("<persons>... </persons>", "12", "2 ")
<Person> StartElement (, "person", null, "{Attributes }")
"\ N \ t" Characters ("<persons>... </persons>", "31", "3 ")
<Name> StartElement (, "name", null, "{Attributes }")
"Li Ming" Characters ("<persons>... </persons>", "40", "2 ")
</Name> EndElement ("", "name", null)
"\ N \ t" Characters ("<persons>... </persons>", "50", "3 ")
<Age> StartElement (, "age", null, "{Attributes }")
"30" Characters ("<persons>... </persons>", "58", "2 ")
</Age> EndElement ("", "age", null)
"\ N \ t" Characters ("<persons>... </persons>", "67", "2 ")
</Person> EndElement ("", "person", null)
"\ N \ t" Characters ("<persons>... </persons>", "79", "2 ")
Repeated <person> ....
{Document ended} EndDocument ()

 

Example 1: Read the content in the XML file and construct the content into a Person object. Then, read the content in the XML file and add the Person object to a List set:
Person class:

Public class Person {
 

 
Private Integer id;
 
Private String name;
 
Private short age;
 

 
Public Integer getId (){
 
Return id;
 
}
 
Public void setId (Integer id ){
 
This. id = id;
 
}
 

 
Public String getName (){
 
Return name;
 
}
 
Public void setName (String name ){
 
This. name = name;
 
}
 

 
Public short getAge (){
 
Return age;
 
}
 
Public void setAge (short age ){
 
This. age = age;
 
}
 

 
@ Override
 
Public String toString (){
 
Return "Person [age =" + age + ", id =" + id + ", name =" + name + "]";
 
}
 

 
}

 
Business bean:

Public class SAXPersonService {
 
Public static List <Person> readXml (InputStream inputStream)
 
Throws Exception {
 

 
// Get a SAXParserFactory object
 
SAXParserFactory spf = SAXParserFactory. newInstance ();
 
// Parses the object using SAX.
 
SAXParser saxParser = spf. newSAXParser ();
 

 
// ContentHandler object
 
XMLContentHandler handler = new XMLContentHandler ();
 

 
// Start Parsing
 
SaxParser. parse (inputStream, handler );
 
// Close the stream www.2cto.com
 
InputStream. close ();
 

 
Return handler. getPersons ();
 

 
}
 
}

 
XMLContentHandler inherits from DefalutHander and DefaultHandler implements the ContentHandler interface.

/**
 
* Inherited from DefaultHandler, this class also implements ContentHandler.
 
* @ Author Administrator
 
*
 
*/
 
Public class XMLContentHandler extends DefaultHandler {
 

 
Private List <Person> persons;
 
Private Person person;
 
Private String preTag; // The current tag.
 

 
Public List <Person> getPersons (){
 
Return persons;
 
}
 

 
/**
 
* Document start
 
*/
 
Public void startDocument () throws SAXException {
 
Persons = new ArrayList <Person> ();
 
}
 

 
/**
 
* Read document content
 
*/
 
Public void characters (char [] ch, int start, int length)
 
Throws SAXException {
 

 
If (person! = Null ){
 
String data = new String (ch, start, length );
 
// Determine whether the preceding element is "name"
 
If ("name". equals (preTag )){
 
Person. setName (data );
 
} Else if ("age". equals (preTag )){
 
Person. setAge (new Short (data ));
 
}
 
}
 

 
}
 

 
/**
 
* Element start
 
*/
 
Public void startElement (String uri, String localName, String qName,
 
Attributes attributes) throws SAXException {
 
// Determine whether the parsed element is equal to "person"
 
If ("person". equals (localName )){
 
Person = new Person ();
 
// Person. setId (Integer. parseInt (attributes. getValue (0 )));
 
Person. setId (Integer. parseInt (attributes. getValue ("", "id ")));
 
}
 
// Current element
 
PreTag = localName;
 
}
 

 
/**
 
* After parsing an element, add it to the List.
 
*/
 
Public void endElement (String uri, String localName, String qName)
 
Throws SAXException {
 
If ("person". equals (localName) & person! = Null ){
 
Persons. add (person );
 
Person = null;
 
}
 
// Set the current element to null.
 
PreTag = null;
 
}
 
}

 
Test:

Public class SAXPersonServiceTest extends AndroidTestCase {
 

 
Private static final String TAG = "LogTest ";
 
Public void testSAXReadXml () throws Exception {
 
// Obtain the input stream from the resource file
 
InputStream inputStream = SAXPersonServiceTest. class. getClassLoader ()
 
. GetResourceAsStream ("itcast. xml ");
 
List <Person> list = SAXPersonService. readXml (inputStream );
 
For (Person person: list ){
 
System. out. println (person );
 
}
 
}
 
}
 

From jiahui524 Column
 
 

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.