XmlPullParser解析xml数据

前端之家收集整理的这篇文章主要介绍了XmlPullParser解析xml数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

解析assets目录下的persons.xml文件

<?xml version="1.0" encoding="UTF-8"?>  
<persons>  
    <person id="1001">  
        <name> 路人甲</name>  
        <age>25</age>  
    </person>  
    <person id="1002">  
        <name>路人乙</name>  
        <age>26</age>  
    </person>  
</persons>  


public class MainActivity extends Activity {

	private TextView textView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView = (TextView) findViewById(R.id.textView);
		textView.setText("");
		try {
			AssetManager assetManager = null;
			assetManager = this.getAssets();
			ParseTools3 parseTools = new ParseTools3();
			parseTools.setTextView(textView);
			parseTools.getRooms(assetManager.open("persons.xml"));
		} catch (Exception e) {
			Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
			textView.append(e.toString());
			e.printStackTrace();
		}
	}
}


package com.example.xmltestdemo;

import java.io.InputStream;
import org.xmlpull.v1.XmlPullParser;
import android.util.Xml;
import android.widget.TextView;

public class ParseTools3 {

	private TextView textView;

	public void setTextView(TextView textView) {
		this.textView = textView;
	}

	public void getRooms(InputStream xml) throws Exception {
		XmlPullParser pullParser = Xml.newPullParser();
		pullParser.setInput(xml,"UTF-8");
		int event = pullParser.getEventType();
		while (event != XmlPullParser.END_DOCUMENT) {
			switch (event) {
			case XmlPullParser.START_DOCUMENT:
				print("开始解析......\n");
				break;
			case XmlPullParser.START_TAG:
				String name = pullParser.getName();
				String value;
				if (name.equals("persons")) {
					value = "persons\n";
				} else if (name.equals("person")) {
					value = "person\n";
					value = pullParser.getAttributeValue(0);
					name = pullParser.getAttributeName(0);
				} else {
					value = pullParser.nextText();
				}
				if (name != null) {
					if (value != null) {
						print(name + "=" + value);
					}
				}
				if (name == null || value == null) {
					print("[0]");
				}
				break;
			case XmlPullParser.END_TAG:
				if (pullParser.getName() != null
						&& pullParser.getName().equals("person")) {
					print("end " + pullParser.getName() + "\n");
				} else if (pullParser.getName() != null
						&& pullParser.getName().equals("persons")) {
					print("end " + pullParser.getName() + "\n");
				}
				break;
			default:
				// 空白或者换行
				print("; ");
				break;
			}
			event = pullParser.next();
		}
	}

	private void print(String text) {
		textView.append(text);
	}

}

运行结果:


本文参考:

http://blog.csdn.net/liuhe688/article/details/6415593

原文链接:https://www.f2er.com/xml/296591.html

猜你在找的XML相关文章