Objective
This article mainly describes how to parse XML files in Android. The main use is the sax mechanism, sax is all called Simple APIs for XML, which is both an interface and a software package. As an interface, sax is a standard interface for event-driven XML parsing. There are generally 2 ways to parse XML files, Dom and sax. The DOM needs to read all the XML documents into the computer's memory first, and the method does not apply when the document is too large. Sax solves the problem better, and it is parsed on a line-by-row basis and can be interrupted at any time. But sax operations are more complex. Therefore, these 2 methods each have advantages and disadvantages, see the specific application. In the previous Article QT Learning path _12 (simple Data management System) uses the DOM method in Qt.
Experimental instructions
Most sax implementations produce events similar to the following:
Triggers the document processing event at the beginning and end of the document, triggering element events before and after each XML element in the document is resolved, and any metadata that is usually the result of individual events delivered by soybean oil; a DTD or schema event is generated when processing a document's DTD or schema ; An error event is used to notify the host application of parsing errors.
The SAX model diagram looks like this:
If you want to parse an XML document with sax, you need a class to inherit the ContentHandler class provided by the Android system. But if you inherit contenthandler this class, even if you do not use all the methods provided by this class, you must implement all of its internal methods (generally not used methods can be directly replaced by a null method), but this is not very convenient to develop. So we can inherit defaulthandler this class, so that we only need to implement the method required in the program, and other methods within the class has actually been replaced by a null method.
There are several ways to ContentHandler interfaces:
void Startdocument ()//When document resolution starts
void Enddocument ()//When document parsing ends
void Startelement (String uri, String localname, String qName, Attributes atts);//When the label starts parsing
void EndElement (String uri, String localname, String qName, Attributes atts);//execution at end of label resolution
void characters (char[] ch, int start, int length);
Using Sax to parse XML files in Android, you need to first create a sax factory, the SAXParserFactory object, and a XmlReader object that binds ContentHandler subclasses and combines with XML source files. The process is to create an event handler, create a SAX parser, assign the key event handler to the parser, parse the document, and send each event to the handler.
The equal method of the string class is used to determine whether string values are equal.
This experiment is to parse a section of XML code and then print some of the content in each of the analytic functions above. The main is to learn how to use the SAX model to create a parser, how to use the ContentHandler subclass of the function to parse.
The main part of the experiment Code:
Mainactivity.java:
Copy Code code as follows:
Package com.example.xml;
Import Java.io.StringReader;
Import Javax.xml.parsers.SAXParserFactory;
Import Org.xml.sax.InputSource;
Import Org.xml.sax.XMLReader;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.TextView;
public class Mainactivity extends activity {
Private Button start = null;
Private TextView display = null;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Start = (Button) Findviewbyid (R.id.start);
Start.setonclicklistener (New Startonclicklistener ());
}
public class Startonclicklistener implements onclicklistener{
public void OnClick (View v) {
TODO auto-generated Method Stub
Note 2, 1th: If you want to wrap lines in a string, you should add quotes and plus signs to get them, and you can't write them directly.
2nd: If there are characters in the string, replace the quotes with (\) inside the brackets.
The XML file I used here directly layout the layout XML file for this program
String Result_str =
"<relativelayout" +
"Xmlns:tools=\" http://schemas.android.com/tools\ "" +
"Android:layout_width=\" match_parent\ "" +
"Android:layout_height=\" match_parent\ ">" +
//
"<button" +
"Android:id=\" @+id/start\ "" +
"Android:layout_width=\" fill_parent\ "" +
"Android:layout_height=\" wrap_content\ "" +
"Android:layout_alignparentbottom=\" true\ "" +
"Android:text=\" Start XML parse\ "" +
"/>" +
"<textview" +
"Android:id=\" @+id/display\ "" +
"Android:layout_width=\" fill_parent\ "" +
"Android:layout_height=\" fill_parent\ "" +
"Android:gravity=\" Center\ "" +
"Android:layout_alignparentleft=\" true\ "" +
"Android:layout_above=\" @+id/start\ "" +
"Android:text=\" the XML Parse example!! \" " +
"/>" +
"</RelativeLayout>";
String Result_str =
"<button" +
"Id=\" @+id/start\ "" +
"Layoutwidth=\" fillparent\ "" +
"Layoutheight=\" wrapcontent\ "" +
"Layoutalignparentbottom=\" true\ "" +
"Text=\" Start XML parse\ "" +
"</Button>";
System.out.println (RESULT_STR);
try{
Create a sax factory
SAXParserFactory factory = Saxparserfactory.newinstance ();
XMLReader reader = Factory.newsaxparser (). Getxmlreader ();
Reader.setcontenthandler (New Mycontenthandler ());
Reader.parse (new InputSource) (New StringReader (RESULT_STR));
}
catch (Exception e) {
E.printstacktrace ();
}
}
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Getmenuinflater (). Inflate (R.menu.activity_main, menu);
return true;
}
}
Mycontenthandler.java:
Copy Code code as follows:
Package com.example.xml;
Import org.xml.sax.Attributes;
Import org.xml.sax.SAXException;
Import Org.xml.sax.helpers.DefaultHandler;
public class Mycontenthandler extends DefaultHandler {
String tagname, sid, Swidth, Sheight, text, salign;
This method is called when parsing to the label's property bar
@Override
public void characters (char[] ch, int start, int length)
Throws Saxexception {
TODO auto-generated Method Stub
if (Tagname.equals ("id"))
Sid = New String (CH, start, length);
else if (tagname.equals ("Layoutwidth"))
Swidth = new String (CH, start, length);
else if (tagname.equals ("Layoutheight"))
Sheight = new String (CH, start, length);
else if (tagname.equals ("Layoutalignparentbottom"))
Salign = new String (CH, start, length);
else if (tagname.equals ("text"))
Text = new String (CH, start, length);
Super.characters (CH, start, length);
}
Parse Document End Call
@Override
public void Enddocument () throws Saxexception {
TODO auto-generated Method Stub
System.out.println (".........");
Super.enddocument ();
}
//parsing label at the end of call
@Override
public void EndElement ( String uri, String localname, string QName
Throws Saxexception {
//TODO auto-generated method stub
if (tagname.equals ("button")) {
this.printout ();
}
super.endelement (URI, LocalName, QName);
}
Called when parsing a document starts
@Override
public void Startdocument () throws Saxexception {
TODO auto-generated Method Stub
SYSTEM.OUT.PRINTLN ("... begin .......");
Super.startdocument ();
}
Execute when label starts
@Override
public void Startelement (string uri, String localname, String qName,
Attributes Attributes) throws Saxexception {
TODO auto-generated Method Stub
TagName = LocalName;
if (Tagname.equals ("button")) {
for (int i = 0; i < attributes.getlength (); i++) {
Get the name and value of the first attribute
System.out.println (Attributes.getlocalname (i) + "=" + Attributes.getvalue (i));
}
}
Super.startelement (URI, LocalName, qName, attributes);
}
Output label attribute resolution result
private void printout () {
System.out.print ("ID:");
SYSTEM.OUT.PRINTLN (SID);
System.out.print ("Layout_width:");
System.out.println (Swidth);
System.out.print ("Layout_height:");
System.out.println (Sheight);
System.out.print ("Layout_alignparentbottom:");
System.out.println (salign);
System.out.print ("text:");
System.out.println (text);
}
}