Preface
This article describes how to parse XML files in Android. It mainly uses the SAX mechanism, which is called Simple API for XML. It is both an interface and a software package. As an interface, SAX is a standard interface for event-driven XML parsing. XML file parsing generally involves two methods: DOM and SAX. The DOM must first read all xml documents into the computer memory. This method is not applicable when the document content is too large. SAX solves this problem better. It is parsed row by row and can be interrupted at any time. However, the operations of SAX are complicated. Therefore, the two methods have their own advantages and disadvantages, depending on the specific application. In the previous article, the DOM method in Qt is used in the path _ 12 (simple data management system.
Lab description
Most SAX implementations generate events similar to the following:
Trigger the Document Processing Event at the beginning and end of the document; trigger the element event before and after each XML Element in the document ends parsing; Any metadata is usually delivered separately; a dtd or Schema event is generated when processing the document's DTD or Schema. An error event is generated to notify the Host application of parsing errors.
The SAX model is as follows:
If you want to use SAX to parse xml documents, you need a class to inherit the ContentHandler class provided by the android system. However, if you inherit the ContentHandler class, even if you do not use all the methods provided by this class, you must also implement all internal methods (generally, empty methods can be used instead of unused methods), but this development is not very convenient. Therefore, we can inherit the DefaultHandler class instead. In this way, we only need to implement the methods required in the program. Other methods are actually replaced by empty methods in the class.
The ContentHandler interface has the following methods:
Void startDocument (); // executed at the beginning of document Parsing
Void endDocument (); // executed at the end of document Parsing
Void startElement (String uri, String localName, String qName, Attributes atts); // executed when the tag is parsed
Void endElement (String uri, String localName, String qName, Attributes atts); // executed at the end of Tag Parsing
Void characters (char [] ch, int start, int length); // executed when parsing tag attributes
In android, if you use SAX to parse xml files, you must first create a SAX factory, that is, the SAXParserFactory object. You also need to create an XMLReader object, which is bound to the ContentHandler subclass and combined with the xml source file. That is, 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 values of the String type are equal.
This experiment parses an xml code and prints some content in each of the above parsing functions. The main idea is to learn how to use the SAX model to create a parser and how to use the ContentHandler subclass function for parsing.
Code of the experiment:
Mainactivity. java:
Copy codeThe Code is 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: 1st: If you want to wrap a string, you should use quotation marks and the plus sign to add it. You cannot directly wrap it.
// 2nd: if the character string contains characters, use the '\' in the brackets to replace the quotation marks.
// The xml file I used here is the layout xml file of layout.
// 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 codeThe Code is 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 the attribute bar of the tag is parsed.
@ 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 the document to end the call
@ Override
Public void endDocument () throws SAXException {
// TODO Auto-generated method stub
System. out. println .......");
Super. endDocument ();
}
// Call when TAG resolution ends
@ 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 at the beginning of parsing the document
@ Override
Public void startDocument () throws SAXException {
// TODO Auto-generated method stub
System. out. println .......");
Super. startDocument ();
}
// Executed when the tag 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 ++ ){
// Obtain the name and value of the I-th attribute
System. out. println (attributes. getLocalName (I) + "=" + attributes. getValue (I ));
}
}
Super. startElement (uri, localName, qName, attributes );
}
// Output the tag property parsing 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 );
}
}