Serialization generation and parsing of XML files in Android

Source: Internet
Author: User
Tags xml parser

First, I put the entity class of person

Package net.loonggg.test;      public class Person {private int id;      Private String age;      private String name;      Private String sex;        Private String address;      public int getId () {return id;      } public void setId (int id) {this.id = ID;      } public String Getage () {return age;      public void Setage (String age) {this.age = age;      } public String GetName () {return name;      } public void SetName (String name) {this.name = name;      } public String Getsex () {return sex;      public void Setsex (String sex) {this.sex = sex;      } public String getaddress () {return address;      The public void setaddress (String address) {this.address = address;                  } @Override Public String toString () {return ' person [id= + ID + ', age= "+ Age +", name= "+ Name + ", sex= "+ Sex +", address= "+ address +"] ";   }    }
Second: The method for generating the XML file is as follows:

/** * Generates XML */private void Createxml () {XmlSerializer serializer = Xml.newserializer ();//XML File Raw          Generator file = new file (Environment.getexternalstoragedirectory (), "person.xml");          FileOutputStream fos = null;              try {fos = new FileOutputStream (file); Serializer.setoutput (FOS, "utf-8");//Set output stream and character encoding for XML generator serializer.startdocument ("Utf-8", true);//Start document. The parameters are character encoding and whether to maintain independent serializer.starttag (NULL, "persons");                  Start tags, which are: namespace and label name for (person person:list) {Serializer.starttag (null, "man");                    Serializer.attribute (NULL, "id", Person.getid () + ""); Serializer.starttag (NULL, "name");//start Tag Serializer.text (Person.getname ());//text content Seri                  Alizer.endtag (NULL, "name");//end tag Serializer.starttag (null, "sex"); Serializer.text (Person.getsex ());                    Serializer.endtag (null, "sex");                  Serializer.starttag (NULL, "age");                  Serializer.text (Person.getage ());                    Serializer.endtag (NULL, "age");                  Serializer.starttag (NULL, "address");                  Serializer.text (Person.getaddress ());                    Serializer.endtag (NULL, "address");                Serializer.endtag (null, "person"); } Serializer.endtag (NULL, "persons");//end tag serializer.enddocument ();//end XML document to Ast.maketext (Getapplicationcontext (), "Build succeeded.          ", Toast.length_short); } catch (Exception e) {toast.maketext (Getapplicationcontext (), "Build failed!

", Toast.length_short); E.printstacktrace (); } finally {try {fos.close (); } catch (IOException e) {e.printstacktrace (); } } }

Then there is the way to parse the XML file:

/** * Parse XML file */private list<person> Pullxml () {try {File file = new file (En              Vironment.getexternalstoragedirectory (), "person.xml");              FileInputStream fis = new FileInputStream (file);              list<person> persons = NULL;              person person = null;              Xmlpullparser parser = Xml.newpullparser ();//Get XML parser parser.setinput (FIS, "utf-8");//input stream and character encoding, respectively              int type = Parser.geteventtype (); while (type! = xmlpullparser.end_document) {//Assuming the event is not equal to the document end event, continue looping the switch (type) {case X MlPullParser.START_TAG:if ("Persons". Equals (Parser.getname ())) {persons =                      New Arraylist<person> ();                          } else if (' person '. Equals (Parser.getname ())) {person = new person ();           String id = parser.getattributevalue (0);               Person.setid (Integer.parseint (id));                      } else if ("name". Equals (Parser.getname ())) {Person.setname (Parser.nexttext ());                      } else if ("Sex". Equals (Parser.getname ())) {Person.setsex (Parser.nexttext ());                      } else if ("Address". Equals (Parser.getname ())) {person.setaddress (Parser.nexttext ()); } else if ("Age". Equals (Parser.getname ())) {Person.setage (Parser.nexttext ()                      );                  } break; Case XmlPullParser.END_TAG:if ("person". Equals (Parser.getname ())) {persons                          . Add (person);                      person = null;                  } break;          } type = Parser.next ();//Continue next event} return persons; } catch (NumberformatexCeption e) {e.printstacktrace ();          } catch (FileNotFoundException e) {e.printstacktrace ();          } catch (Xmlpullparserexception e) {e.printstacktrace ();          } catch (IOException e) {e.printstacktrace ();      } return null;   }
again is part of the code called in Mainactivity:

public class Mainactivity extends Activity {private Button btn_create = null;      Private Button btn_pull = null;      Private TextView tv_show;        Private list<person> List = null;          @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);          Setcontentview (R.layout.activity_main);          Btn_create = (Button) Findviewbyid (r.id.createxml);          Btn_pull = (Button) Findviewbyid (r.id.pullxml);          Tv_show = (TextView) Findviewbyid (r.id.tvshow);          List = new arraylist<person> ();              for (int i = 0; i < 5; i++) {Person person = new person ();              Person.setage (i + 20 + "");              Person.setid (i);              Person.setname ("LOONGGG" + i);              Person.setsex ("male");              Person.setaddress ("Zhongnanhai" + i + 1 + "Main Street");          List.add (person);                } btn_create.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {createxml ();            }          });  Btn_pull.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v)              {Tv_show.settext (Pullxml (). toString ());      }          });   }  }





Serialization generation and parsing of XML files in Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.