使用PULL解析XML文件

XmlPull和Sax类似,是基于流(stream)操作文件,然后根据节点事件回调开发者编写的处理程序。因为是基于流的处理,因此Xmlpull和 Sax都比较节约内存资源,不会象Dom那样要把所有节点以对橡树的形式展现在内存中。 但Xmlpull比Sax更简明,而且不需要扫描完整个流。

下面来看一个pull解析xml的例子:

student.xml:

 

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <root>
  3. <studentid="1"group="1">
  4. <name>张三</name>
  5. <sex></sex>
  6. <age>18</age>
  7. <email>[email protected]</email>
  8. <birthday>1987-06-08</birthday>
  9. <memo>好学生</memo>
  10. </student>
  11. <studentid="2"group="2">
  12. <name>李四</name>
  13. <sex></sex>
  14. <age>18</age>
  15. <email>[email protected]</email>
  16. <birthday>1987-06-08</birthday>
  17. <memo>好学生</memo>
  18. </student>
  19. <studentid="3"group="3">
  20. <name>小王</name>
  21. <sex></sex>
  22. <age>18</age>
  23. <email>[email protected]</email>
  24. <birthday>1987-06-08</birthday>
  25. <memo>好学生</memo>
  26. </student>
  27. <studentid="4"group="4">
  28. <name>小张</name>
  29. <sex></sex>
  30. <age>18</age>
  31. <email>[email protected]</email>
  32. <birthday>1987-06-08</birthday>
  33. <memo>好学生</memo>
  34. </student>
  35. <studentid="5"group="5">
  36. <name>小明</name>
  37. <sex></sex>
  38. <age>18</age>
  39. <email>[email protected]</email>
  40. <birthday>1987-06-08</birthday>
  41. <memo>好学生</memo>
  42. </student>
  43. </root>
<?xml version="1.0" encoding="utf-8"?>  
    <root>  
        <student id="1" group="1">  
            <name>张三</name>  
            <sex>男</sex>  
            <age>18</age>  
            <email>[email protected]</email>  
            <birthday>1987-06-08</birthday>  
            <memo>好学生</memo>  
        </student>  
        <student id="2" group="2">  
            <name>李四</name>  
            <sex>女</sex>  
            <age>18</age>  
            <email>[email protected]</email>  
            <birthday>1987-06-08</birthday>  
            <memo>好学生</memo>  
        </student>  
        <student id="3" group="3">  
            <name>小王</name>  
            <sex>男</sex>  
            <age>18</age>  
            <email>[email protected]</email>  
            <birthday>1987-06-08</birthday>  
            <memo>好学生</memo>  
        </student>  
        <student id="4" group="4">  
            <name>小张</name>  
            <sex>男</sex>  
            <age>18</age>  
            <email>[email protected]</email>  
            <birthday>1987-06-08</birthday>  
            <memo>好学生</memo>  
        </student>  
        <student id="5" group="5">  
            <name>小明</name>  
            <sex>男</sex>  
            <age>18</age>  
            <email>[email protected]</email>  
            <birthday>1987-06-08</birthday>  
            <memo>好学生</memo>  
        </student>  
    </root>  

对应的bean:

 

  1. public class Student {
  2. private int id;
  3. private int group;
  4. private String name;
  5. private String sex;
  6. private int age;
  7. private String email;
  8. private String memo;
  9. private String birthday;
  10. public int getId() {
  11. return id;
  12. }
  13. public void setId(int id) {
  14. this.id = id;
  15. }
  16. public int getGroup() {
  17. return group;
  18. }
  19. public void setGroup(int group) {
  20. this.group = group;
  21. }
  22. public String getName() {
  23. return name;
  24. }
  25. public void setName(String name) {
  26. this.name = name;
  27. }
  28. public String getSex() {
  29. return sex;
  30. }
  31. public void setSex(String sex) {
  32. this.sex = sex;
  33. }
  34. public int getAge() {
  35. return age;
  36. }
  37. public void setAge(int age) {
  38. this.age = age;
  39. }
  40. public String getEmail() {
  41. return email;
  42. }
  43. public void setEmail(String email) {
  44. this.email = email;
  45. }
  46. public String getMemo() {
  47. return memo;
  48. }
  49. public void setMemo(String memo) {
  50. this.memo = memo;
  51. }
  52. public String getBirthday() {
  53. return birthday;
  54. }
  55. public void setBirthday(String birthday) {
  56. this.birthday = birthday;
  57. }
  58. }
public class Student {  
    
    private int id;  
    private int group;  
    private String name;  
    private String sex;  
    private int age;  
    private String email;  
    private String memo;  
    private String birthday;  
    public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    public int getGroup() {  
        return group;  
    }  
    public void setGroup(int group) {  
        this.group = group;  
    }  
    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 int getAge() {  
        return age;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
    public String getEmail() {  
        return email;  
    }  
    public void setEmail(String email) {  
        this.email = email;  
    }  
    public String getMemo() {  
        return memo;  
    }  
    public void setMemo(String memo) {  
        this.memo = memo;  
    }  
    public String getBirthday() {  
        return birthday;  
    }  
    public void setBirthday(String birthday) {  
        this.birthday = birthday;  
    }  
      
}  


主要的解析和现实类:

 

  1. import java.io.InputStream;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.xmlpull.v1.XmlPullParser;
  5. import org.xmlpull.v1.XmlPullParserFactory;
  6. import android.app.Activity;
  7. import android.os.Bundle;
  8. import android.os.Handler;
  9. import android.os.Message;
  10. import android.view.ViewGroup.LayoutParams;
  11. import android.widget.LinearLayout;
  12. import android.widget.TextView;
  13. public class PullActivity extends Activity implements Runnable{
  14. private TextView pullTextView ;
  15. private LinearLayout layout;
  16. private Handler handler=new Handler(){
  17. public void handleMessage(android.os.Message msg) {
  18. List<Student>lists=(List<Student>) msg.obj;
  19. for(int i=0;i<lists.size();i++){
  20. Student student=lists.get(i);
  21. StringBuffer sb=new StringBuffer();
  22. sb.append(student.getId()+" ").append(student.getName()+" ")
  23. .append(student.getAge()+" ").append(student.getSex()+" ").append(student.getBirthday()+" ")
  24. .append(student.getEmail()+" ").append(student.getGroup()+" ");
  25. TextView txt=new TextView(getApplicationContext());
  26. txt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
  27. txt.setText(sb.toString());
  28. layout.addView(txt);
  29. }
  30. };
  31. };
  32. @Override
  33. protected void onCreate(Bundle savedInstanceState) {
  34. // TODO Auto-generated method stub
  35. super.onCreate(savedInstanceState);
  36. setContentView(R.layout.pull);
  37. pullTextView=(TextView) this.findViewById(R.id.pullTextView);
  38. layout=(LinearLayout) this.findViewById(R.id.layout);
  39. new Thread(this).start();
  40. }
  41. //pull解析xml
  42. public List<Student> pullParseXml(){
  43. List<Student>lists=null;
  44. Student student=null;
  45. try {
  46. XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
  47. //获取XmlPullParser实例
  48. XmlPullParser pullParser=factory.newPullParser();
  49. InputStream in=this.getClass().getClassLoader().getResourceAsStream("student.xml");
  50. pullParser.setInput(in, "UTF-8");
  51. //开始
  52. int eventType=pullParser.getEventType();
  53. while(eventType!=XmlPullParser.END_DOCUMENT){
  54. String nodeName=pullParser.getName();
  55. switch (eventType) {
  56. //文档开始
  57. case XmlPullParser.START_DOCUMENT:
  58. lists=new ArrayList<Student>();
  59. break;
  60. //开始节点
  61. case XmlPullParser.START_TAG:
  62. if("student".equals(nodeName)){
  63. student=new Student();
  64. student.setId(Integer.parseInt(pullParser.getAttributeValue(0)));
  65. student.setGroup(Integer.parseInt(pullParser.getAttributeValue(1)));
  66. }else if("name".equals(nodeName)){
  67. student.setName(pullParser.nextText());
  68. }else if("sex".equals(nodeName)){
  69. student.setSex(pullParser.nextText());
  70. }else if("age".equals(nodeName)){
  71. student.setAge(Integer.parseInt(pullParser.nextText()));
  72. }else if("email".equals(nodeName)){
  73. student.setEmail(pullParser.nextText());
  74. }else if("birthday".equals(nodeName)){
  75. student.setBirthday(pullParser.nextText());
  76. }else if("memo".equals(nodeName)){
  77. student.setMemo(pullParser.nextText());
  78. }
  79. break;
  80. //结束节点
  81. case XmlPullParser.END_TAG:
  82. if("student".equals(nodeName)){
  83. lists.add(student);
  84. student=null;
  85. }
  86. break;
  87. default:
  88. break;
  89. }
  90. // 手动的触发下一个事件
  91. eventType=pullParser.next();
  92. }
  93. } catch (Exception e) {
  94. // TODO Auto-generated catch block
  95. e.printStackTrace();
  96. }
  97. return lists;
  98. }
  99. @Override
  100. public void run() {
  101. // TODO Auto-generated method stub
  102. List<Student>lists=pullParseXml();
  103. Message msg=handler.obtainMessage();
  104. msg.obj=lists;
  105. handler.sendMessage(msg);
  106. }
  107. }
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

import android.widget.TextView;

public class PullActivity extends Activity implements Runnable{

	private TextView pullTextView ;
	private LinearLayout layout;
	private Handler handler=new Handler(){
		 public void handleMessage(android.os.Message msg) {
			 List<Student> lists=(List<Student>) msg.obj;
			 for(int i=0;i<lists.size();i++){
				 Student student=lists.get(i);
				 StringBuffer sb=new StringBuffer();
				 sb.append(student.getId()+"  ").append(student.getName()+"  ")
				 .append(student.getAge()+"  ").append(student.getSex()+" ").append(student.getBirthday()+"  ")
				 .append(student.getEmail()+"  ").append(student.getGroup()+"  ");
				 TextView txt=new TextView(getApplicationContext());
				 txt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				 txt.setText(sb.toString());
				 layout.addView(txt);
			 }
		 };
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pull);
		
		pullTextView=(TextView) this.findViewById(R.id.pullTextView);
		layout=(LinearLayout) this.findViewById(R.id.layout);
		new Thread(this).start();
		
		 
		 
	}
	//pull解析xml
	public List<Student> pullParseXml(){
		List<Student> lists=null;
		Student student=null;
		
		try {
			XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
			//获取XmlPullParser实例
			XmlPullParser pullParser=factory.newPullParser();
			InputStream in=this.getClass().getClassLoader().getResourceAsStream("student.xml");
			pullParser.setInput(in, "UTF-8");
			//开始
			int eventType=pullParser.getEventType();
			
			while(eventType!=XmlPullParser.END_DOCUMENT){
				String nodeName=pullParser.getName();
				switch (eventType) {
				//文档开始
				case XmlPullParser.START_DOCUMENT:
					 lists=new ArrayList<Student>();
					break;

					//开始节点
				case XmlPullParser.START_TAG:
					if("student".equals(nodeName)){
						student=new Student();
						student.setId(Integer.parseInt(pullParser.getAttributeValue(0)));
						student.setGroup(Integer.parseInt(pullParser.getAttributeValue(1)));
					}else if("name".equals(nodeName)){
						student.setName(pullParser.nextText());
					}else if("sex".equals(nodeName)){
						student.setSex(pullParser.nextText());
					}else if("age".equals(nodeName)){
						student.setAge(Integer.parseInt(pullParser.nextText()));
					}else if("email".equals(nodeName)){
						student.setEmail(pullParser.nextText());
					}else if("birthday".equals(nodeName)){
						student.setBirthday(pullParser.nextText());
					}else if("memo".equals(nodeName)){
						student.setMemo(pullParser.nextText());
					}
					break;
					//结束节点
				case XmlPullParser.END_TAG:
					if("student".equals(nodeName)){
						lists.add(student);
						student=null;
					}
					break;
				default:
					break;
				}
				 // 手动的触发下一个事件  
				eventType=pullParser.next();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lists;
		
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		List<Student> lists=pullParseXml();
		Message msg=handler.obtainMessage();
		msg.obj=lists;
		handler.sendMessage(msg);
	}
}

注意xml中的<?xml version="1.0" encoding="utf-8"?> 这句话要顶格显示,不要留空隙,附则错了很难调试的。

解析后效果:

使用PULL解析XML文件

你可能感兴趣的:(解析xml)