Read and write XML files with XmlSerializer and Xmlpullparser
Here's what XmlSerializer writes to the XML file in Phone memory:
Public voidWriteXML () {File file=NewFile ( This. Getfilesdir (), "Test.xml"); XmlSerializer s=Xml.newserializer (); Try{FileOutputStream fos=Newfileoutputstream (file); S.setoutput (FOS,"Utf-8"); S.startdocument ("Utf-8",NULL); S.starttag (NULL, "persons"); for(inti=0;i<10;i++) {S.starttag (NULL, "P"); S.starttag (NULL, "name"); S.text ("Ah" +string.valueof (i)); S.endtag (NULL, "name"); S.starttag (NULL, "Age"); S.text (String.valueof (+i)); S.endtag (NULL, "Age"); S.endtag (NULL, "P"); } S.endtag (NULL, "persons"); S.enddocument (); Fos.flush (); Fos.close (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }
Here is the contents of the XML file that Xmlpullparser reads in the phone memory:
PublicList<person>ReadXML () {list=NULL; Person P=NULL; File File=NewFile ( This. Getfilesdir (), "Test.xml"); Xmlpullparser Parser=Xml.newpullparser (); Try{FileInputStream fis=Newfileinputstream (file); Parser.setinput (FIS,"Utf-8"); intEventtype=Parser.geteventtype (); while(eventtype!=xmlpullparser.end_document) {String TagName=Parser.getname (); Switch(eventtype) { CaseXmlpullparser.start_tag:if("Persons". Equals (TagName)) {List=NewArraylist<person>(); }Else if("P". Equals (TagName)) {P=NewPerson (); }Else if("Name". Equals (TagName)) {P.setname (Parser.nexttext ()); }Else if("Age". Equals (TagName)) {P.setage (Integer.parseint (Parser.nexttext ())); } Break; CaseXmlpullparser.end_tag:if("P". Equals (TagName)) {List.add (P); } Break; default: Break; } EventType=Parser.next (); } fis.close (); } Catch(Exception e) {e.printstacktrace (); } returnlist; }
Android Beginner note--xml file read and write