(Android Review) Parsing and serialization of XML

Source: Internet
Author: User


This blog is mainly used to describe the operation of XML files: parsing and generating.


Internal analysis of Android phone is pull parsing
Official website: http://xmlpull.org/
The so-called parsing, we can understand as: the use of XML file content to generate an object
Do not format the generated XML file after exporting it, otherwise it will be out of the ordinary


1, Mainactivity

Package Com.example.xmlparsertest1;import Android.os.bundle;import Android.app.activity;import android.view.Menu; public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}


2. Person

Package Com.example.xmlparsertest1;public class Person {private integer id;private String name;private integer age; Public person () {//TODO auto-generated constructor stub}public person (integer ID, String name, Integer age) {super (); . id = id;this.name = Name;this.age = age;} Public Integer GetId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public Integer Getage () {return age;} public void Setage (Integer age) {this.age = age;} @Overridepublic String toString () {return "person [id=" + ID + ", name=" + name + ", age=" + Age + "]";}}


3, Personservice

Package Com.example.xmlparsertest1;import Java.io.inputstream;import Java.io.outputstream;import Java.util.arraylist;import Java.util.list;import Org.xmlpull.v1.xmlpullparser;import Org.xmlpull.v1.XmlSerializer Import Android.util.xml;public class Personservice {/** * parse Xml file * @param in * @return * @throws Exception */public List <Person> loadpersons (InputStream in) throws Exception{xmlpullparser parser = Xml.newpullparser ();// Get parser Parser.setinput (in, "UTF-8");//Specify input stream, code table arraylist<person> persons = new arraylist<person> (); Person p = null;/** * Parser.getname (): Gets the name of the tag * Parser.getattributevalue (0): Gets the value of a property * Parser.next (): Let the pointer point to the next label * Parse R.nexttext (): Gets the text content of a label */for (int type = Parser.geteventtype (); Type! = xmlpullparser.end_document; type = Parser.next ()) {if (type = = Xmlpullparser.start_tag) {if (Parser.getname (). Equals ("person")) {p = new person (); String id = parser.getattributevalue (0);//Gets the value of the No. 0 property of the label (value)//string id = parser.getattributevalue (NULL, "id");//ThisIt's OK to write. The first parameter is the namespace, the second parameter is the name of the property P.setid (Integer.parseint (ID));p ersons.add (p);} else if (Parser.getname () equals ("name")) {String name = Parser.nexttext ();p. SetName (name);} else if (Parser.getname () Equals ("Age")) {String age = Parser.nexttext ();p. Setage (Integer.parseint);}} return persons;} Generate XML file public void Savepersons (list<person> persons,outputstream out) throws Exception{xmlserializer Serializer = Xml.newserializer (); Serializer.setoutput (out, "UTF-8"); Serializer.startdocument ("UTF-8", true);// Start document Serializer.starttag (NULL, "persons");//start Tag/** * serializer.startdocument ("UTF-8", true);//Start document * Serializer.starttag (NULL, "persons");//start tag * Serializer.attribute (NULL, "id", P.getid (). toString ());//Set properties * Serializer.text (P.getname ());//Set the text contents of the label * SERIALIZER.ENDTAG (NULL, "persons"); * Serializer.enddocument (); */for (person p:persons) {Serializer.starttag (null, ' person '); Serializer.attribute (NULL, "id", P.getid (). toString ()) ;//Set property Serializer.starttag (null, "name"); Serializer.text (P.getnaMe ());//Set the text content of the label Serializer.endtag (NULL, "name"), Serializer.starttag (null, "age"), Serializer.text (P.getage (). ToString ()); Serializer.endtag (null, "age"); Serializer.endtag (null, ' person ');} Serializer.endtag (NULL, "persons"); Serializer.enddocument ();}}


4, Personservicetest

Package Com.example.xmlparsertest1;import Java.io.fileoutputstream;import Java.io.inputstream;import Java.util.list;import Android.os.environment;import Android.test.androidtestcase;public class PersonServiceTest Extends Androidtestcase {public void Testxmlparser () throws Exception{personservice service = new Personservice ();// Gets the resource for the SRC directory as the input stream method InputStream in = PersonServiceTest.class.getClassLoader (). getResourceAsStream ("Persons_hjd.xml") ; list<person> persons = Service.loadpersons (in), for (person p:persons) {System.out.println ("----------->" + P) ;} Person p = new person (4, "Hjd",//persons.add (p);////service.savepersons (persons, New FileOutputStream ( Environment.getexternalstoragedirectory () + "/" + "Persons_hjd.xml"));}}


The following XML files need to be parsed: persons.xml

<?xml version= ' 1.0 ' encoding= ' UTF-8 ' standalone= ' yes '? ><persons><person id= "1" ><name> Fan Bingbing </name><age>31</age></person><person id= "2" ><name> Lin Chi-ling </name><age >38</age></person><person id= "3" ><name> Yang mi </name><age>26</age></ Person></persons>



SOURCE Download: http://download.csdn.net/detail/caihongshijie6/7616863



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.