Android SAX parses xml files

Source: Internet
Author: User

Android
1. First understand some terms in the xml file
Xml Code
<? Xml version = "1.0" encoding = "UTF-8"?>
<Persons>
<Person id = "23">
<Name> Li Ming </name>
<Age> 23 </age>
</Person>
<Person id = "22">
<Name> Li Quan </name>
<Age> 25 </age>
</Person>
</Persons>


The labels and content in xml can be called nodes, and the persons person name age in xml are called elements ). the values like Li Ming 25 are called text nodes. so what is between <persons> and <person>? The answer is that he is also a node. It is a text node. You will say there is nothing in it. Wrong, it has carriage return and space. you can debug the xml parsing in the sax file. press enter and space (or tab) will be read. id is a property.
2. sax
The event-driven mechanism of sax means that it does not need to fully read the xml file. It resolves whether a node conforms to the xml syntax when reading a node, if yes, the corresponding method is called and there is no memory function. the methods mentioned below are all in the ContentHander () interface.
Startjavasnet (): this event is triggered when the xml file declaration is parsed, and initialization can be performed.
StartElement () triggers this event when the start tag of the element is parsed.
Characters () triggers this event when reading text elements.
EndElement () triggers this event when the end tag is read.

Sax is parsed in order.
3. Examples of reading xml files by using sax
3-1 create a project ReadXml
3-2 copy the xml file to the root directory.
Xml Code
<? Xml version = "1.0" encoding = "UTF-8"?>
<Persons>
<Person id = "23">
<Name> Li Ming </name>
<Age> 23 </age>
</Person>
<Person id = "22">
<Name> Li Quan </name>
<Age> 25 </age>
</Person>
</Persons>

It can be seen that there is an abstract object in this xml file, that is, the person property has an id name age.
Then we create a bean.
3-3: Create bean
Java code
Package com. leequer. service. demo;
/**
* <Person id = "23">
<Name> Li Ming </name>
<Age> 23 </age>
</Person>
<Person id = "22">
<Name> Li Quan </name>
<Age> 25 </age>
</Person>
* @ Author leequer
*
* Bean corresponding to the xml file
*/
Public class Person {

Private Integer id;
Private String name;
Private int age;

Public Person ()
{}
Public Person (String name, int age)
{
This. name = name;
This. age = 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 int getAge (){
Return age;
}
Public void setAge (int age ){
This. age = age;
}
@ Override
Public String toString (){
// TODO Auto-generated method stub
Return this. id + ", name" + this. name + "age" + this. age + "\ n ";
}

}


3-4: Following the mvc Architecture, we create a service to read xml
Java code
Package com. leequer. service;

Import java. io. InputStream;
Import java. util. List;


Import javax. xml. parsers. SAXParser;
Import javax. xml. parsers. SAXParserFactory;

Import org. xml. sax. XMLReader;



Import com. leequer. service. demo. Person;

Public class SaxReadxml {
Public static List <Person> readXml (InputStream inStream) throws Exception {
SAXParserFactory spf = SAXParserFactory. newInstance (); // initialize the sax Parser
SAXParser sp = spf. newSAXParser (); // create a sax Parser
// XMLReader xr = sp. getXMLReader (); // create an xml Parser
XMLContentHandler handler = new XMLContentHandler ();
Sp. parse (inStream, handler );
Return handler. getPersons ();
}
}


Sp. parse (inStream, handler );
This sentence shows that the xml file is passed in as a stream, and the handler parameter is an instance of the callback function, when the sax Parser parses an xml file, when it encounters xml-compliant content, it will go to the handle class to call the corresponding method mentioned above. then we need to establish the XMLContentHandler to require this class to implement the ContentHandler () interface, but this interface has many implementation methods. sax provides a DefaultHandler interface. You only need to implement the method you are interested in.

3-5: Create XMLContentHandler and complete the implementation of the read events. Note that the annotations are used.
Java code
Package com. leequer. service;

Import java. util. ArrayList;
Import java. util. List;

Import org. xml. sax. Attributes;
Import org. xml. sax. SAXException;
Import org. xml. sax. helpers. DefaultHandler;

Import com. leequer. service. demo. Person;

Public class XMLContentHandler extends DefaultHandler {
Private List <Person> persons;

Private Person person;
Private String tempString;
Private static final String NAMESTRING = "name ";
Private static final String AGESTRING = "age ";
Private static final String PERSONSTRING = "person ";
Private static final String IDSTRING = "id ";

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

/**
* The sax parsing file only reads <person id = "23"> <name> Li Ming </name> <age> 23 </age>
* </Person> <person id = "22"> <name> Li Quan </name> <age> 25 </age> </person>
* If this part contains the start and end of the person node element, there must be startElement and endElement.
* These two methods also have the node elements of text, that is, text elements such as carriage return and space between nodes, and text such as Li Ming in labels.
* (Text node element) the characters method is used to obtain information to parse the text node element .)
*/
/**
* Method called to start reading xml files
* Initialize persons
*/
@ Override
Public void startDocument () throws SAXException {
// Initialize the list.
Persons = new ArrayList <Person> ();
}

/**
* This method is called when sax reads data to a text node.
*/
@ Override
Public void characters (char [] ch, int start, int length)
Throws SAXException {

If (person! = Null ){
String valueString = new String (ch, start, length );
If (NAMESTRING. equals (tempString )){
// If the resolved node is name, the text node element in name must be worth
Person. setName (valueString );
} Else if (AGESTRING. equals (tempString )){
Person. setAge (new Integer (valueString). intValue ());
}
}
}
/**
* This method is used when sax reads element nodes;
*/
@ Override
Public void startElement (String uri, String localName, String name,
Attributes attributes) throws SAXException {
// First judge whether the read element is person
If (PERSONSTRING. equals (localName )){
// If we read the person element, we need to save it and store it in the person class we created. So we need to create a new person class.
Person = new Person ();
// Attributes is an attribute.
Person. setId (new Integer (attributes. getValue (IDSTRING )));
}
TempString = localName;

}
/**
* This method is executed every time the tag is terminated. It is not called only at the end.
*
* After reading, the end of the person object will be saved to the list and the person object will be cleared.
*
*/

@ Override
Public void endElement (String uri, String localName, String name)
Throws SAXException {
If (PERSONSTRING. equals (localName) & person! = Null)
{
Persons. add (person );
Person = null;
}
TempString = null;

}




}


3-6: Write a test class to load the xml file in the experiment and then read
Package com. leequer. readxml;
/**
* Test class
*/
Import java. io. InputStream;
Import java. util. Iterator;
Import java. util. List;
 
Import com. leequer. service. SaxReadxml;
Import com. leequer. service. demo. Person;
 
Import android. test. AndroidTestCase;
Import android. util. Log;
 
Public class SaxReadxmlTest extends AndroidTestCase {
Private String PERSONSTRING = "ObjectPerson ";
Public void testReadXml () throws Exception
{// Class Loader
InputStream inputStream = SaxReadxmlTest. class. getClassLoader (). getResourceAsStream ("NewFile. xml ");

List <Person> personsList = SaxReadxml. readXml (inputStream );

For (Iterator iterator = personsList. iterator (); iterator. hasNext ();){
Person person = (Person) iterator. next ();
Log. I (PERSONSTRING, person. toString ());
}

}
}

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.