1. 程式人生 > >Android學習記錄(1)—Android中XML檔案的序列化生成與解析

Android學習記錄(1)—Android中XML檔案的序列化生成與解析

xml檔案是非常常用的,在android中json和xml是非常常用的兩種封裝資料的形式,從伺服器中獲取資料也經常是這兩種形式的,所以學會生成和解析xml和json是非常有用的,json相對來說是比較簡單的,咱不做介紹了,這裡給大家講一下xml的序列化生成和解析。不廢話了,先上圖,看怎麼生成圖中的xml資料。


首先,我把Person的實體類給大家貼出來,這個非常簡單,我就不過多解釋了,直接看程式碼就行了。

Person.java,程式碼如下:

package net.loonggg.test;

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

	public int getId() {
		return id;
	}

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

	public String getAge() {
		return age;
	}

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

	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 String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", age=" + age + ", name=" + name
				+ ", sex=" + sex + ", address=" + address + "]";
	}

}

其次:生成xml檔案的方法如下:
/**
	 * 生成xml
	 */
	private void createXml() {
		XmlSerializer serializer = Xml.newSerializer();// xml檔案生成器
		File file = new File(Environment.getExternalStorageDirectory(),
				"person.xml");
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			serializer.setOutput(fos, "utf-8");// 為xml生成器設定輸出流和字元編碼
			serializer.startDocument("utf-8", true);// 開始文件,引數分別為字元編碼和是否保持獨立
			serializer.startTag(null, "persons"); // 開始標籤,引數分別為:名稱空間和標籤名
			for (Person person : list) {

				serializer.startTag(null, "person");
				serializer.attribute(null, "id", person.getId() + "");

				serializer.startTag(null, "name");// 開始標籤
				serializer.text(person.getName());// 文字內容
				serializer.endTag(null, "name");// 結束標籤

				serializer.startTag(null, "sex");
				serializer.text(person.getSex());
				serializer.endTag(null, "sex");

				serializer.startTag(null, "age");
				serializer.text(person.getAge());
				serializer.endTag(null, "age");

				serializer.startTag(null, "address");
				serializer.text(person.getAddress());
				serializer.endTag(null, "address");

				serializer.endTag(null, "person");

			}
			serializer.endTag(null, "persons");// 結束標籤
			serializer.endDocument();// 結束xml文件
			Toast.makeText(getApplicationContext(), "生成成功!", Toast.LENGTH_SHORT);
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "生成失敗!", Toast.LENGTH_SHORT);
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

然後是解析xml檔案的方法:
/**
	 * 解析xml檔案
	 */
	private List<Person> pullXml() {
		try {
			File file = new File(Environment.getExternalStorageDirectory(),
					"person.xml");
			FileInputStream fis = new FileInputStream(file);
			List<Person> persons = null;
			Person person = null;
			XmlPullParser parser = Xml.newPullParser();// 獲取xml解析器
			parser.setInput(fis, "utf-8");// 引數分別為輸入流和字元編碼
			int type = parser.getEventType();
			while (type != XmlPullParser.END_DOCUMENT) {// 如果事件不等於文件結束事件就繼續迴圈
				switch (type) {
				case XmlPullParser.START_TAG:
					if ("persons".equals(parser.getName())) {
						persons = new ArrayList<Person>();
					} else if ("person".equals(parser.getName())) {
						person = new Person();
						String id = parser.getAttributeValue(0);
						person.setId(Integer.parseInt(id));
					} else if ("name".equals(parser.getName())) {
						person.setName(parser.nextText());
					} else if ("sex".equals(parser.getName())) {
						person.setSex(parser.nextText());
					} else if ("address".equals(parser.getName())) {
						person.setAddress(parser.nextText());
					} else if ("age".equals(parser.getName())) {
						person.setAge(parser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					if ("person".equals(parser.getName())) {
						persons.add(person);
						person = null;
					}
					break;
				}
				type = parser.next();// 繼續下一個事件
			}
			return persons;
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

再次是MainActivity裡呼叫的部分程式碼:
public class MainActivity extends Activity {
	private Button btn_create = null;
	private Button btn_pull = null;
	private TextView tv_show;
	private List<Person> list = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn_create = (Button) findViewById(R.id.createXml);
		btn_pull = (Button) findViewById(R.id.pullXml);
		tv_show = (TextView) findViewById(R.id.tvShow);
		list = new ArrayList<Person>();
		for (int i = 0; i < 5; i++) {
			Person person = new Person();
			person.setAge(i + 20 + "");
			person.setId(i);
			person.setName("loonggg" + i);
			person.setSex("男");
			person.setAddress("中南海" + i + 1 + "大街");
			list.add(person);
		}
		btn_create.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				createXml();
			}
		});

		btn_pull.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				tv_show.setText(pullXml().toString());
			}
		});
	}
}

最後是佈局檔案,程式碼如下;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/createXml"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="生成xml" />

    <Button
        android:id="@+id/pullXml"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="解析xml" />

    <TextView
        android:id="@+id/tvShow"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

到這裡就完了,很簡單吧!

程式碼下載地址:

http://download.csdn.net/detail/loongggdroid/6725669