First, there are three ways to parse an XML file in Android, Dom,sax,pull
Here we'll talk about pull, and later on sax and Dom.
Pull is an event-driven XML parsing method that does not need to parse the entire document, the returned value is numeric, and is the recommended parsing method
Look at the code:
XML file
<?XML version= "1.0" encoding= "UTF-8"?><Persons> < PersonID= "All"> <name>Sun Yangyang</name> < Age>30</ Age> </ Person> < PersonID= " the"> <name>Binbin Sun</name> < Age>25</ Age> </ Person></Persons>
Parsing code:
Private voidReadXml ()throwsIOException, xmlpullparserexception {File xmlfile=NewFile ("/data/person.xml");//Get FileXmlpullparser parser = Xml.newpullparser ();//New ParserFileInputStream input =NewFileInputStream (xmlfile);//Get input streamParser.setinput (Input, "UTF-8");//set the input stream to the parser intevent = Parser.geteventtype ();//Get Event Type while(Event! = xmlpullparser.end_document)//start operating on a time type { Switch(event) { CaseXmlPullParser.START_TAG:String Nam= Parser.getname ();//get the tag name and compare it to the name to give the value to Sname if(Nam.equals ("name") ) {sname+=Parser.nexttext (); } Break; CaseXmlPullParser.END_TAG:name.setText (sname);//set up sname for TextView Break; } Event= Parser.next ();//Step in } //Name.settext (sname);Input.close (); }
Simple use of Pull parsing xml file in Android