XML file parsing
XML parsing:XML technology is the application base of Android platform,
Android provides a variety of ways to parse XML: Sax parsing, Dom parsing, pull parsing
Sax parsing
SAX --simple API Forxml (XML simple API)
-Fast resolution and low memory consumption
--Provides a simple set of APIs for parsing XML files
--sax before parsing an XML file, specify a parse event handler (Handler) thatSax will scan the XML document in a simple sequential sequence, when scanning to the start and end of document, element The start and end of the " tag tag" sends a message to the previously specified parsing event handler, which is processed by the processor to handle the corresponding event. when the XML document is scanned, the entire parsing process is complete.
Sax parsing methods
- Create a factory object for the SAX parser
Saxparserfactory.newinstance
- Creating a SAXParser Parser object
Saxparserfactory.newinstance
- This method is triggered at the beginning of an XML document
Defaulthandler.startdocument ()
- This method is triggered at the end of an XML document
Defaulthandler.enddocument ()
- This method is triggered when the element starts
Defaulthandler.startelement (String uri, String localname, String qName, Attributes Attributes)
- This method is triggered when the element starts
Defaulthandler.endelement (String uri, String localname, String qName, Attributes Attributes)
Parameters:
Uri: namespace
LocalName: Label name without a namespace
QName: Label name with namespace
Attributes: All property and attribute values
- This method is triggered when the element content is read
DefaultHandler. Characters (char [] ch, int start, int length)
Sax parsing Code
Custom XML files are stored in the Res/raw file
1 Public voidonCreate (Bundle savedinstancestate) {2 Super. OnCreate (savedinstancestate);3SAXParserFactory spf=saxparserfactory.newinstance ();//the factory object of the SAX parser4 Try {5SAXParser Sp=spf.newsaxparser ();//Sax Parser Object6 //Read Resource file7InputStream is=getresources (). Openrawresource (R.raw.book);8 //To create a Sax event handler object9DefaultHandler dh=NewDefaultHandler () {Ten PrivateString name; One Public voidstartelement (String uri, string localname, A String qName, Attributes Attributes) - throwssaxexception { -Name=LocalName; the } - //Get content - Public voidCharacters (Char[] ch,intStartintlength) - throwssaxexception { + if("Name". Equals (name)) {//when the label signature is name, go to get the text -Toast.maketext (Sax0.thi S,NewString (ch,start,length), 1000). Show (); +Name=NULL; A } at } - }; - Sp.parse (is, DH); -}Catch(parserconfigurationexception e) {e.printstacktrace (); -}Catch(saxexception e) {e.printstacktrace (); -}Catch(IOException e) {e.printstacktrace (); } in}
Sax Parsing
XML file parsing "Android 7"--sax parsing