The examples in this article describe using SAX to parse XML. Typically, using sax and Dom,dom in Android requires that the entire XML file be read into memory and then parsed, which consumes memory, while Sax is an event-driven process that triggers callback functions at each node, but sax is suitable for XML documents with simple node structure, Complex XML documents can be a bit of a hassle in later node depth processing.
The Test.xml files to be resolved in this article are as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<test>
<title>testSAX</title>
< Content aa= "1" bb= "2" >
<name>hellogv</name>
<url>http://blog.csdn.net/hellogv</ url>
</content>
</test>
The results of parsing XML like this are shown in the following illustration:
Using SAX parsing, you need to define SAXPARSERFACTORY (enabling applications to configure and get a SAX based parser to parse XML documents), SAXParser (parsing XML from various input sources), XMLReader (using callback functions to read XML documents), Among them XmlReader is a key. XmlReader can define various callback functions for parsing XML, triggering these callback functions when conditions are met.
SAXParserFactory factory = Saxparserfactory.newinstance ();
SAXParser parser = Factory.newsaxparser ();
XMLReader reader = Parser.getxmlreader ();
Reader.setcontenthandler (handler);
Reader.parse (New InputSource (TestSAX.this.getResources ()
. Openrawresource (R.raw.test)));
In this code, XmlReader invokes the Saxhandler that inherits DefaultHandler. DefaultHandler has implemented interfaces such as ContentHandler, Dtdhandler, Entityresolver, and ErrorHandler, containing common XML-reading operations, Please see the following Saxhandler.java source code specifically.
The results of the resulting XML are shown in the following illustration:
After reading each node, the above illustration uses XmlSerializer to regroup and output the XML string.
The Main.xml code for this article is as follows:
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
android:orientation=" vertical "android:layout_width=" fill_parent "
android:layout_height=" Fill_parent ">
<button android:layout_height=" wrap_content "android:layout_width=" Fill_parent "
Android:id= "@+id/btnsax"
android:text= "parsing xml with sax" ></Button>
<button android:layout_height= "Wrap_content"
android:layout_width= "fill_parent" android:text= "Generate XML" android:id= "@+id/btnoutput" ></ button>
<edittext android:text= "@+id/edittext01" android:id= "@+id/edittext01"
android:layout_ Width= "Fill_parent" android:layout_height= "fill_parent" ></EditText>
</LinearLayout>
Saxhandler.java source code is as follows:
Package com.testsax;
Import java.util.ArrayList;
Import org.xml.sax.Attributes;
Import org.xml.sax.SAXException;
Import Org.xml.sax.helpers.DefaultHandler;
Import Android.util.Log; public class Saxhandler extends defaulthandler{private arraylist<string> keys = new arraylist<string> ();// Save field name Private arraylist<object> values = new arraylist<object> ()//Save value @Override public void Startdocume
NT () throws Saxexception {super.startdocument ();
@Override public void Enddocument () throws Saxexception {super.enddocument (); @Override public void Startelement (string uri, String localname, String qName, Attributes Attributes) throws Saxexce
ption {//Save start Tag Keys.add ("Starttag");
Values.add (LocalName);
LOG.E ("Starttag", localname);
Save property value for (int i = 0; i < attributes.getlength (); i++) {Keys.add ("Attr");
String[] Str=new string[2];
Str[0]=attributes.getlocalname (i);
Str[1]=attributes.getvalue (i);
Values.add (str); LOG.E ("Attr", str[0]+ "=" +str[1]); @Override public void EndElement (string uri, String localname, String qName) throws Saxexception {//Save end tag K
Eys.add ("Endtag");
Values.add (LocalName);
LOG.E ("Endtag", localname); @Override public void characters (char[] ch, int start, int length) throws Saxexception {String value = new String
(CH, start, length);
Value = Value.trim ();
if (value.length () = = 0) return;
Keys.add ("text");
Values.add (value);
LOG.E ("text", value);
Public arraylist<string> Getkeys () {return keys;
Public arraylist<object> GetValues () {return values;
}
}
The source code for the
Testsax.java is as follows:
Package com.testsax;
Import Java.io.StringWriter;
Import Javax.xml.parsers.SAXParser;
Import Javax.xml.parsers.SAXParserFactory;
Import Org.xml.sax.InputSource;
Import Org.xml.sax.XMLReader;
Import Org.xmlpull.v1.XmlSerializer;
Import android.app.Activity;
Import Android.os.Bundle;
Import android.util.Xml;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
The public class Testsax extends activity {/** called the ' when ' is the ' The activity ' is a-a-created, btnsax;
EditText Memo;
Saxhandler handler = new Saxhandler ();
@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Btnsax = (Button) This.findviewbyid (r.id.btnsax);
Btnsax.setonclicklistener (New Clickevent ());
Btnoutput = (Button) This.findviewbyid (r.id.btnoutput);
Btnoutput.setonclicklistener (New Clickevent ());
Memo = (edittext) This.findviewbyid (r.id.edittext01); Class Clickevent implements VIEW.ONclicklistener {@Override public void OnClick (View v) {if (v = = btnsax) {//parse XML, and save tag, property equivalent try {SAXPARSERFAC
Tory factory = Saxparserfactory.newinstance ();
SAXParser parser = Factory.newsaxparser ();
XMLReader reader = Parser.getxmlreader ();
Reader.setcontenthandler (handler);
Reader.parse (New InputSource (TestSAX.this.getResources (). Openrawresource (R.raw.test))); catch (Exception ee) {} else if (v = = btnoutput) {//Generate XML try {XmlSerializer serializer = Xml.newserializer (
);
StringWriter writer = new StringWriter ();
try {serializer.setoutput (writer);
Serializer.startdocument ("UTF-8", true); for (int i=0;i
Interested readers can do their own debugging run this example code, I hope that the Android project for everyone to play a reference role.