我爱编程

XML解析之PULL

2016-11-11  本文已影响0人  A_Coder

<?xml version="1.0" encoding="UTF-8"?>    
<students>    
    <student id="101">    
        <name>小明</name>    
        <age>18</age>    
    </student>    
    <student id="102">    
        <name>小李</name>    
        <age>19</age>    
    </student>     
</students>    
public class Student{  

    //学号
    private int id;
      
    //姓名  
    private String name;  
    //年龄  
    private String age;  

    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public String getAge() {  
        return age;  
    }  
  
    public void setAge(String age) {  
        this.age = age;  
    }  
  
    @Override  
    public String toString() {  
        return "学生: 年龄=" + age + ", 姓名=" + name + ";";  
    }  
}  
public interface StudentParser {  
    /** 
     * 解析输入流 得到Student对象集合 
     * @param is 
     * @return 
     * @throws Exception 
     */  
    public List<Student> parse(InputStream is) throws Exception;  
  
    /** 
     * 序列化Student对象集合 得到XML形式的字符串 
     * @param students 
     * @return 
     * @throws Exception 
     */  
    public String serialize(List<Student> students) throws Exception;  
}  
public class StudentParserImpl implements StudentParser{  
  
    @Override  
    public List<Student> parse(InputStream is) throws Exception {  
        List<Student> mList = null;  
        Student student= null;  
          
        // 由android.util.Xml创建一个XmlPullParser实例  
        XmlPullParser parser = Xml.newPullParser();  
        // 设置输入流 并指明编码方式  
        parser.setInput(is,"UTF-8");  
        // 产生第一个事件  
        int eventType = parser.getEventType();  
          
        while (eventType != XmlPullParser.END_DOCUMENT){  
             switch (eventType) {  
                         // 判断当前事件是否为文档开始事件  
                         case XmlPullParser.START_DOCUMENT:  
                             mList = new ArrayList<Student>(); // 初始化Student集合  
                             break;  
                         // 判断当前事件是否为标签元素开始事件  
                         case XmlPullParser.START_TAG:  
                             if (parser.getName().equals("student")) { // 判断开始标签元素是否是student
                                 student = new Student();  
                             }  else if (parser.getName().equals("id")) {  
                                      eventType = parser.next();  
                                      student.setId(Integer.parseInt(parser.getText()));  
                            }  else if (parser.getName().equals("name")) {  
                                 eventType = parser.next();//让解析器指向name属性的值  
                                 // 得到name标签的属性值,并设置student的name  
                                 student.setName(parser.getText());  
                           } else if (parser.getName().equals("age")) { 
                                 eventType = parser.next();//让解析器指向age属性的值  
                                 // 得到age标签的属性值,并设置student的age  
                                 student.setAge(parser.getText());  
                           }   
                             break;  
                
                         // 判断当前事件是否为标签元素结束事件  
                         case XmlPullParser.END_TAG:  
                             if (parser.getName().equals("student")) { // 判断结束标签元素是否是student
                                 mList.add(student); // 将student添加到students集合  
                                 student = null;  
                             }  
                             break;  
                         }  
                         // 进入下一个元素并触发相应事件  
                         eventType = parser.next();  
                     }  
                     return mList;    
        }  
    
    @Override  
    public String serialize(List<Student> students) throws Exception {  
        // TODO Auto-generated method stub  
        XmlSerializer serializer = Xml.newSerializer(); //由android.util.Xml创建一个XmlSerializer实例  
        StringWriter writer = new StringWriter();  
        serializer.setOutput(writer);   //设置输出方向为writer  
        serializer.startDocument("UTF-8", true);  
        serializer.startTag("", "students");  
        for (Student student : students) {  
            serializer.startTag("", "student");  
            serializer.attribute("", "id", student .getId() + "");  
  
            serializer.startTag("", "name");  
            serializer.text(student.getName());  
            serializer.endTag("", "name");  
  
            serializer.startTag("", "price");  
            serializer.text(student.getPrice() + "");  
            serializer.endTag("", "price");  
  
            serializer.endTag("", "student");  
        }  
        serializer.endTag("", "students");  
        serializer.endDocument();  
  
        return writer.toString();   
    }  
  
}  
public class MainActivity extends Activity {  
  
    private static final String TAG = "XML";  
  
    private StudentParser parser;  
    private List<Student> studnents;  
  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
  
        Button readBtn = (Button) findViewById(R.id.readBtn);  
        Button writeBtn = (Button) findViewById(R.id.writeBtn);  
  
        readBtn.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                try {  
                    InputStream is = getAssets().open("students.xml");  
                    parser = new StudentParser();  //创建StudentParser实例  
                    students = parser.parse(is);  //解析输入流  
                    for (Student student : students) {  
                        Log.i(TAG, student.toString());  
                    }  
                } catch (Exception e) {  
                    Log.e(TAG, e.getMessage());  
                }  
            }  
        });  
        writeBtn.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                try {  
                    String xml = parser.serialize(students);  //序列化  
                    FileOutputStream fos = openFileOutput("students.xml", Context.MODE_PRIVATE);  
                    fos.write(xml.getBytes("UTF-8"));  
                } catch (Exception e) {  
                    Log.e(TAG, e.getMessage());  
                }  
            }  
        });  
    }  
}  
上一篇下一篇

猜你喜欢

热点阅读