Suppose I want to parse the following XML file:
1 <?XML version= "1.0" encoding= "UTF-8"?>2 <Books>3 < Book Price= "99.0"Publication date= "2008">Crazy Java Handouts</ Book>4 < Book Price= "199.0"Publication date= "2009">Crazy Android Handout</ Book>5 < Book Price= "79.0"Publication date= "2010">Crazy Handouts</ Book>6 </Books>
First put the file in the Res/xml folder, if you can not manually establish, and then parse the code as follows:
1 Public voidXmlparser (View v) {2 3Xmlresourceparser Xmlresourceparser = Getresources (). GETXML (R.xml.books);//gets the parser for the XML file4 Try {5StringBuilder SB =NewStringBuilder ();6 while(Xmlresourceparser.geteventtype ()! = xmlresourceparser.end_document) {//if not at the end of the document7 if(Xmlresourceparser.geteventtype () = = Xmlresourceparser.start_tag) {//If you encounter the start tag of a tag, start reading the class capacity8 //get the label's signature9String TagName =xmlresourceparser.getname ();Ten if(Tagname.equals ("book")) { One AString bookprice = xmlresourceparser.getattributevalue (0);//gets the value of the first property in the label, which is the value of "price" -String bookdata = xmlresourceparser.getattributevalue (1);//gets the value of the second property in the label, which is the value of "Publication date" -String bookname = Xmlresourceparser.nexttext ();//get the value of the text node, here is the name of the book the -Sb.append ("Price:"); - sb.append (bookprice); -Sb.append ("Date of publication:"); + sb.append (bookdata); -Sb.append ("title:"); + sb.append (bookname); ASb.append ("\ n"); at } - - } -Xmlresourceparser.next ();//gets the next event of the parser - - } in - Textview.settext (sb.tostring ()); to +}Catch(xmlpullparserexception e) { - e.printstacktrace (); the *}Catch(IOException e) { $ e.printstacktrace ();Panax Notoginseng } - the}
The parsed results are as follows:
How to parse XML in Android