Android Development (7) -- parsing XML files by using SAX in Android

Source: Internet
Author: User

1. Write an xml file in the assets File
[Html] v
<? 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>

<? 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>
2. Write a SAX-parsed class in the service

[Java]
Package com. example. 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. example. domain. Person;

Public class XMLContentHandlerextends DefaultHandler {

// The resolved person object is stored in the list set.
Private List <Person> persons;
// Parse the current person object
Public Person currentPerson;
// Declare the Tag Name
Public String tagName;


// Obtain and parse all person objects
Public List <Person> getPersons (){
Return persons;
}

@ Override
Public void characters (char [] ch, int start, int length)
Throws SAXException {

Super. characters (ch, start, length );
// First, judge whether the tagName is empty.
If (tagName! = Null ){
String data = new String (ch, start, length );
// Determine whether the tag is empty
If (tagName. equals ("name ")){
CurrentPerson. setName (data );
} Else if (tagName. equals ("age") {// determine whether the tag is age
CurrentPerson. setAge (short) Integer. parseInt (data ));
}
}
}

@ Override
Public void endDocument () throws SAXException {

Super. endDocument ();
}

@ Override
Public void endElement (String uri, String localName, String qName)
Throws SAXException {

Super. endElement (uri, localName, qName );
// Store the person object to the collection when the person Tag ends
If (localName. equals ("person ")){
Persons. add (currentPerson );
CurrentPerson = null;
}

This. tagName = null;
}

/**
* Events triggered at the beginning of the document
*/
@ Override
Public void startDocument () throws SAXException {

Super. startDocument ();
Persons = new ArrayList <Person> ();
}

@ Override
Public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {

Super. startElement (uri, localName, qName, attributes );
// Determine whether the parsed tag is person
If (localName. equals ("person ")){
CurrentPerson = new Person ();
// Parse the value of the id attribute and assign the id value to the currentPerson object
CurrentPerson. setId (Integer. parseInt (attributes. getValue (0 )));
}

This. tagName = localName;
}

}
[Java]
Package com. example. 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. example. domain. Person;
 
Public class XMLContentHandler extends DefaultHandler {
 
// The resolved person object is stored in the list set.
Private List <Person> persons;
// Parse the current person object
Public Person currentPerson;
// Declare the Tag Name
Public String tagName;


// Obtain and parse all person objects
Public List <Person> getPersons (){
Return persons;
}

@ Override
Public void characters (char [] ch, int start, int length)
Throws SAXException {

Super. characters (ch, start, length );
// First, judge whether the tagName is empty.
If (tagName! = Null ){
String data = new String (ch, start, length );
// Determine whether the tag is empty
If (tagName. equals ("name ")){
CurrentPerson. setName (data );
} Else if (tagName. equals ("age") {// determine whether the tag is age
CurrentPerson. setAge (short) Integer. parseInt (data ));
}
}
}
 
@ Override
Public void endDocument () throws SAXException {

Super. endDocument ();
}
 
@ Override
Public void endElement (String uri, String localName, String qName)
Throws SAXException {

Super. endElement (uri, localName, qName );
// Store the person object to the collection when the person Tag ends
If (localName. equals ("person ")){
Persons. add (currentPerson );
CurrentPerson = null;
}

This. tagName = null;
}
 
/**
* Events triggered at the beginning of the document
*/
@ Override
Public void startDocument () throws SAXException {

Super. startDocument ();
Persons = new ArrayList <Person> ();
}
 
@ Override
Public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {

Super. startElement (uri, localName, qName, attributes );
// Determine whether the parsed tag is person
If (localName. equals ("person ")){
CurrentPerson = new Person ();
// Parse the value of the id attribute and assign the id value to the currentPerson object
CurrentPerson. setId (Integer. parseInt (attributes. getValue (0 )));
}

This. tagName = localName;
}

}

Package com. example. 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. example. domain. Person;

Public class XMLContentHandler extends DefaultHandler {

// The resolved person object is stored in the list set.
Private List <Person> persons;
// Parse the current person object
Public Person currentPerson;
// Declare the Tag Name
Public String tagName;


// Obtain and parse all person objects
Public List <Person> getPersons (){
Return persons;
}
 
@ Override
Public void characters (char [] ch, int start, int length)
Throws SAXException {

Super. characters (ch, start, length );
// First, judge whether the tagName is empty.
If (tagName! = Null ){
String data = new String (ch, start, length );
// Determine whether the tag is empty
If (tagName. equals ("name ")){
CurrentPerson. setName (data );
} Else if (tagName. equals ("age") {// determine whether the tag is age
CurrentPerson. setAge (short) Integer. parseInt (data ));
}
}
}

@ Override
Public void endDocument () throws SAXException {

Super. endDocument ();
}

@ Override
Public void endElement (String uri, String localName, String qName)
Throws SAXException {

Super. endElement (uri, localName, qName );
// Store the person object to the collection when the person Tag ends
If (localName. equals ("person ")){
Persons. add (currentPerson );
CurrentPerson = null;
}

This. tagName = null;
}

/**
* Events triggered at the beginning of the document
*/
@ Override
Public void startDocument () throws SAXException {

Super. startDocument ();
Persons = new ArrayList <Person> ();
}

@ Override
Public void startElement (String uri, String localName, String qName,
Attributes attributes) throws SAXException {

Super. startElement (uri, localName, qName, attributes );
// Determine whether the parsed tag is person
If (localName. equals ("person ")){
CurrentPerson = new Person ();
// Parse the value of the id attribute and assign the id value to the currentPerson object
CurrentPerson. setId (Integer. parseInt (attributes. getValue (0 )));
}

This. tagName = localName;
}
 
}
3. Get the operations of the SAX class in the Activity
[Java]
Package com. example. lession03_xml;

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


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

Import com. example. domain. Person;
Import com. example. service. XMLContentHandler;
Import com. example. service. XMLDomService;

 

Import android. OS. Bundle;
Import android. app. Activity;
Import android. view. Menu;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. view. inputmethod. InputBinding;
Import android. widget. Button;
Import android. widget. Toast;

Public class XmlActivityextends Activity {

// Declare the component
Public Button btn_sax, btn_dom, btn_pull;

Public XMLDomService xmlDomService;

@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
// Set the displayed view
SetContentView (R. layout. activity_xml );

XmlDomService = new XMLDomService ();
// Obtain the component by id
Btn_sax = (Button) findViewById (R. id. btn_sax );
Btn_dom = (Button) findViewById (R. id. btn_dom );
Btn_pull = (Button) findViewById (R. id. btn_pull );

// Register an event for the button
Btn_sax.setOnClickListener (new MyOnclickListener ());
Btn_dom.setOnClickListener (new MyOnclickListener ());
Btn_pull.setOnClickListener (new MyOnclickListener ());
}

@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
// Inflate the menu; this adds items to the action bar if it is present.
GetMenuInflater (). inflate (R. menu. xml, menu );
Return true;
}

// Anonymous class
Class MyOnclickListener implements OnClickListener {

@ Override
Public void onClick (View v ){
Int id = v. getId ();
Switch (id ){
Case R. id. btn_sax:
Toast. makeText (XmlActivity. this, "using SAX Parsing", Toast. LENGTH_LONG). show ();
Try {
// The factory object parsed by SAX
SAXParserFactory factory = SAXParserFactory. newInstance ();
// Get the sax Parser
SAXParser saxParser = factory. newSAXParser ();
// Create a handler object
XMLContentHandler handlerService = new XMLContentHandler ();
InputStream is = getAssets (). open ("csdn. xml ");
// Directly parse
SaxParser. parse (is, handlerService );
// Get it through the handlerService object
Toast. makeText (XmlActivity. this, "----" + handlerService, Toast. LENGTH_LONG). show ();
} Catch (Exception e ){
E. printStackTrace ();
}

Break;
Case R. id. btn_dom:

InputStream is = null;
Try {
// Obtain the input stream object for reading the file
Is = getAssets (). open ("csdn. xml ");
// Use dom for parsing
List <Person> persons = xmlDomService. parseXML (is );
// Simple test
// Toast. makeText (XmlActivity. this, "" + persons. get (0). getName (), Toast. LENGTH_LONG). show ();
Toast. makeText (XmlActivity. this, "using DOM Parsing" + persons. get (0). getName (), Toast. LENGTH_LONG). show ();
} Catch (Exception e ){
E. printStackTrace ();
}


Break;
Case R. id. btn_pull:
Toast. makeText (XmlActivity. this, "Use PULL Parsing", Toast. LENGTH_LONG). show ();
Break;

Default:
Break;
}

}

}
}

Bytes ------------------------------------------------------------------------------------------------------------------

 

 

 

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.