Android应用中使用Pull解析XML文件(传智播客)
来源:99网
Service.java源码:
Person.java源码:
- package com.sinaapp.ssun.domain;
-
- public class Person {
- private String name;
- private int age;
- private int id;
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
-
- public Person(String name, int age, int id) {
- this.name = name;
- this.age = age;
- this.id = id;
- }
- public Person() {
- super();
- }
- @Override
- public String toString() {
- return "Person [name=" + name + ", age=" + age + ", id=" + id + "]";
- }
- }
text.xml文件:
-
- <?xml version="1.0" encoding="UTF-8"?>
- <persons>
- <person id="1">
- <name>ssun</name>
- <age>19</age>
- </person>
- <person id="2">
- <name>cobe</name>
- <age>24</age>
- </person>
- </persons>
单元测试TestService.java源码:
- package com.sinaapp.ssun.test;
-
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.util.ArrayList;
- import java.util.List;
-
- import android.test.AndroidTestCase;
- import android.util.Log;
-
- import com.sinaapp.ssun.domain.Person;
- import com.sinaapp.ssun.service.Service;
-
- public class TestService extends AndroidTestCase {
- private final String Tag = "Test";
-
- public void testPersons() throws Exception{
- List<Person> persons = Service.getPersons(this.getClass().getClassLoader().getResourceAsStream("test.xml"));
- for(Person p : persons){
- Log.i(Tag, p.toString());
- }
- }
-
- public void testSave() throws Exception{
- List<Person> persons = new ArrayList<Person>();
- persons.add(new Person("www",19,23));
- persons.add(new Person("hhh",19,3));
- persons.add(new Person("qqq",19,24));
- persons.add(new Person("ooo",19,25));
- File file = new File(this.getContext().getFilesDir(),"test2.xml");
- FileOutputStream out = new FileOutputStream(file);
- Service.save(persons, out);
- }
-
- }
-