Serialization generation and parsing of XML files in Android

Source: Internet
Author: User

Serialization generation and parsing of XML files in Android

First, I put the object 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;      }        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 an xml file is as follows:
/*** Generate xml */private void createXml () {XmlSerializer serializer = Xml. newSerializer (); // xml File generator file File = new File (Environment. getExternalStorageDirectory (), "person. xml "); FileOutputStream fos = null; try {fos = new FileOutputStream (file); serializer. setOutput (fos, "UTF-8"); // set the output stream and character encoding serializer for the xml generator. startDocument ("UTF-8", true); // start document. The parameters are character encoding and whether to maintain independent serializer. startTag (null, "pers Ons "); // start tag. The parameters are namespace and the standard signature for (Person person: list) {serializer. startTag (null, "person"); serializer. attribute (null, "id", person. getId () + ""); serializer. startTag (null, "name"); // start label serializer. text (person. getName (); // serializer of text content. endTag (null, "name"); // end label 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 label serializer. endDocument (); // end the xml document Toast. makeText (getApplicationContext (), "generated successfully! ", Toast. LENGTH_SHORT);} catch (Exception e) {Toast. makeText (getApplicationContext ()," generation failed! ", Toast. LENGTH_SHORT); e. printStackTrace () ;}finally {try {fos. close () ;}catch (IOException e) {e. printStackTrace ();}}}
The method for parsing xml files is as follows:
/*** Parse xml file */private List
 
  
PullXml () {try {File file = new File (Environment. getExternalStorageDirectory (), "person. xml"); FileInputStream FCM = new FileInputStream (file); List
  
   
Persons = null; Person person = null; XmlPullParser parser = Xml. newPullParser (); // get the xml parser. setInput (FCM, "UTF-8"); // The parameters are the input stream and the character encoding int type = parser. getEventType (); while (type! = XmlPullParser. END_DOCUMENT) {// if the event is not equal to the end event of the document, the loop switch (type) {case XmlPullParser will continue. START_TAG: if ("persons ". equals (parser. getName () {persons = new ArrayList
   
    
();} 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 the 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 ;}
   
  
 
The second 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
 
  
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
  
   
(); 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 + ""); 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 ());}});}}
  
 

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.