Android cainiao study note 19 ---- Android data storage (iii) XML file parsing and serialization, android serialization

Source: Internet
Author: User

Android cainiao study note 19 ---- Android data storage (iii) XML file parsing and serialization, android serialization

Android has a built-in XPP3 Implementation of the PULL parser and a SAX Parser. You can directly use PULL or SAX to parse XML and directly use the code for PULL or SAX parsing in JAVA, if you forget it, you can refer to parsing XML in java and 3:

If the following XmlUtils class implements the PULL method to parse XML to List and serialize List to XML:

Student Entity class code:

 1 package cn.csc.bean; 2  3 public class Student { 4  5       private String id; 6  7       private String name; 8  9       private String gender;10 11       private int age;12 13       public String getId() {14 15            return id;16 17       }18 19       public void setId(String id) {20 21            this.id = id;22 23       }24 25       public String getName() {26 27            return name;28 29       }30 31       public void setName(String name) {32 33            this.name = name;34 35       }36 37       public String getGender() {38 39            return gender;40 41       }42 43       public void setGender(String gender) {44 45            this.gender = gender;46 47       }48 49       public int getAge() {50 51            return age;52 53       }54 55       public void setAge(int age) {56 57            this.age = age;58 59       }60 61      62 63       public Student() {64 65            super();66 67       }68 69       public Student(String id, String name, String gender, int age) {70 71            super();72 73            this.id = id;74 75            this.name = name;76 77            this.gender = gender;78 79            this.age = age;80 81       }82 83       @Override84 85       public String toString() {86 87            return "["+id+","+name+","+gender+","+age+"]";88 89       }90 91 }

Code of the XmlUtils class:

  1 public class XmlUtils {  2   3       public static void serialize(Context context, String filename, List<Student> list){  4   5            try {  6   7                  XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  8   9                  XmlSerializer serializer = factory.newSerializer(); 10  11                  serializer.setOutput(context.openFileOutput(filename, Context.MODE_PRIVATE), "utf-8"); 12  13                  serializer.startDocument("utf-8", true); 14  15                  serializer.startTag(null, "students"); 16  17                  for(Student s:list){ 18  19                       serializer.startTag(null, "student"); 20  21                       serializer.attribute(null, "id", s.getId()); 22  23                       serializer.startTag(null, "name"); 24  25                       serializer.text(s.getName()); 26  27                       serializer.endTag(null, "name"); 28  29                       serializer.startTag(null, "gender"); 30  31                       serializer.text(s.getGender()); 32  33                       serializer.endTag(null, "gender"); 34  35                       serializer.startTag(null, "age"); 36  37                       serializer.text(s.getAge()+""); 38  39                       serializer.endTag(null, "age"); 40  41                       serializer.endTag(null, "student"); 42  43                  } 44  45                  serializer.endTag(null, "students"); 46  47                  serializer.endDocument(); 48  49            } catch (Exception e) { 50  51                  // TODO Auto-generated catch block 52  53                  e.printStackTrace(); 54  55            } 56  57       } 58  59       public static List<Student> parse(Context context, String filename){ 60  61            List<Student> list = new ArrayList<Student>(); 62  63            try { 64  65                  XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 66  67                  XmlPullParser parser = factory.newPullParser(); 68  69                  parser.setInput(context.openFileInput(filename), "utf-8"); 70  71                  Student s = null; 72  73                  int eventType = parser.getEventType(); 74  75                  while(eventType != XmlPullParser.END_DOCUMENT){ 76  77                       if(eventType == XmlPullParser.START_TAG){ 78  79                             String tag = parser.getName(); 80  81                             if(tag.equals("student")){ 82  83                                   s = new Student(); 84  85                                   s.setId(parser.getAttributeValue(0)); 86  87                             }else if(tag.equals("name")){ 88  89                                   s.setName(parser.nextText()); 90  91                             }else if(tag.equals("gender")){ 92  93                                   s.setGender(parser.nextText()); 94  95                             }else if(tag.equals("age")){ 96  97                                   s.setAge(Integer.parseInt(parser.nextText())); 98  99                             }100 101                       }else if(eventType == XmlPullParser.END_TAG && parser.getName().equals("student")){102 103                             list.add(s);104 105                       }106 107                       eventType = parser.next();108 109                  }110 111                  for(Student stu : list){112 113                       Log.i("XML_PARSER",stu.toString());114 115                  }116 117            } catch (Exception e) {118 119                  // TODO Auto-generated catch block120 121                  e.printStackTrace();122 123                  return null;124 125            }126 127            return list;128 129       }130 131 }

Use Android Juit to test the two methods:

 1 public class XmlTest extends AndroidTestCase { 2  3       public void testSerializer(){ 4  5            List<Student> list = new ArrayList<Student>(); 6  7            for(int i=0; i<20; i++){ 8  9                  list.add(new Student(i+"","dqrcsc","male",25));10 11            }12 13            XmlUtils.serialize(getContext(), "students.xml", list);14 15       }16 17       public void testParser(){18 19            XmlUtils.parse(getContext(), "students.xml");20 21       }22 23 }

Running result:

 

The above Code, in addition to obtaining Context objects, is exactly the same as parsing xml pull in Java projects.

In fact, Andoid also provides an Xml class in the android. util package to encapsulate XML parsing and serialization operations. It can be relatively simple:

 

These five static methods simplify the PULL parser, PULL serializer, And SAX parsing Operations respectively:

Previous operations on getting the PULL serializer through a factory-class instance can be performed from:

1 XmlPullParserFactory factory = XmlPullParserFactory.newInstance();2 3 XmlSerializer serializer = factory.newSerializer();

Simplified:

XmlSerializer serializer = Xml.newSerializer();

 

You can obtain the PULL parser through a factory instance:

1 XmlPullParserFactory factory = XmlPullParserFactory.newInstance();2 3 XmlPullParser parser = factory.newPullParser();

Simplified:

XmlPullParser parser = Xml.newPullParser();

 

Similarly, SAX Parsing is simplified to directly calling the parse () Static Method of Xml, which is not described here.

 

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.