Menu Home

Android使用Pull解析XML

Andoid解析XML除了传统的DOM和SAX外还提供了一种独有的Pull方式。Pull方式跟SAX非常类似,也使用事件驱动和流式解析,不需要像DOM那样读取整个XML文档。Pull跟SAX最大的区别是:控制解析事件的结束。Pull是由用户主动获取事件进行处理, 这就意味着你可以随时结束解析过程。而在SAX中,SAX解析器会把事件自动推入注册的事件处理器,用户无法控制这个过程。所以对于移动设备这种资源有限的设备来说,Pull方式可以缩短XML解析的时间,因为有时候我们可能只需要处理部分XML后主动结束解析,但这是SAX无法做到的。

一个例子
首先在asserts目录下建立需要解析的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<persons>

    <person id="1" >
        <name>lnmcc</name>
        <age>20</age>
    </person>

    <person id="2" >
        <name>wangsijie</name>
        <age>30</age>
    </person>
    
    <person id="3" >
        <name>Jack</name>
        <age>90</age>
    </person>
    
</persons>


MainActivity.java:

public class MainActivity extends Activity {

	public class Person {
		private int id;
		private String name;
		private int age;

		public void setId(int id) {
			this.id = id;
		}

		public void setName(String name) {
			this.name = name;
		}

		public void setAge(int age) {
			this.age = age;
		}

		public int getId() {
			return id;
		}

		public String getName() {
			return name;
		}

		public int getAge() {
			return age;
		}
		
		@Override
		public String toString() {
			return "Person: id = " + id + " name = " + name + " age = " + age + "\n";
		}
	}

	ArrayList persons = null;
	Person newPerson = null;
	TextView tv = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) findViewById(R.id.textView);
		parseXml();
	}

	private void parseXml() {
		try {
			InputStream inStream = getAssets().open("persons.xml");
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser parser = factory.newPullParser();
			parser.setInput(inStream, "UTF-8");
			int eventType = parser.getEventType();
			boolean docEnd = false;
			
			while (!docEnd) {
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					Log.e("PersonInfo", "Document Start");
					persons = new ArrayList();
					break;
				case XmlPullParser.START_TAG:
					Log.e("PersonInfo", "Tag Start");
					String name = parser.getName();
					if (name.equalsIgnoreCase("person")) {
						newPerson = new Person();
						newPerson.setId(Integer.valueOf(parser
								.getAttributeValue(null, "id")));
					} else if (newPerson != null) {
						if (name.equalsIgnoreCase("name")) {
							newPerson.setName(parser.nextText().trim());
						} else if (name.equalsIgnoreCase("age")) {
							newPerson.setAge(Integer.valueOf(parser.nextText().trim()));
						}
					}
					break;
				case XmlPullParser.END_TAG:
					Log.e("PersonInfo", "Tag End");
					if (newPerson != null
							&& parser.getName().equalsIgnoreCase("person")) {
						persons.add(newPerson);
						newPerson = null;
					}
					break;
				case XmlPullParser.END_DOCUMENT:
					Log.e("PersonInfo", "Document End");
					docEnd = true;
					printPersons(); // 解析完成,输出所以人的信息
					break;
				default:
					break;
				}
				eventType = parser.next();
			}

		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void printPersons() {
		Iterator iter = persons.iterator();
		StringBuffer sb = new StringBuffer();
		while(iter.hasNext()) {
			String info = iter.next().toString();
			Log.e("PersonInfo", info);
			sb.append(info);
		}
		tv.setText(sb.toString());
	}
}

github: https://github.com/lnmcc/ParseXmlUsePull.git

Android使用SAX解析XML在 这里

1 reply