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 + "]";
- }
- }
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 */ 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;
- }
/** * 解析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());
- }
- });
- }
- }
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>
<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
版权声明:本文为博主原创文章,未经博主允许不得转载。