欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android XmlPullParser 方式解析 Xml 文档

程序员文章站 2023-11-16 18:31:58
android xmlpullparser 方式解析 xml 文档 xml 文件格式

android xmlpullparser 方式解析 xml 文档

xml 文件格式

<?xml version="1.0" encoding="utf-8"?>
<persons>
  <person id="1">
    <name>张三</name>
    <age>22</age>
  </person>
  <person id="2">
    <name>李四</name>
    <age>20</age>
  </person>
</persons>

xmlpullparser 方式解析 xml 文件

import java.io.inputstream;
import java.io.outputstream;
import java.util.arraylist;
import java.util.list;
import org.xmlpull.v1.xmlpullparser;
import org.xmlpull.v1.xmlserializer;
import com.eboy.domain.person;
import android.util.xml;
 
public class personservice {
 public static list<person> getpersons(inputstream xml) throws exception {
  list<person> persons = null;
  person person = null;
  xmlpullparser pullparser = xml.newpullparser();
  pullparser.setinput(xml, "utf-8"); // 为pull解释器设置要解析的xml数据
  int event = pullparser.geteventtype();
 
  while (event != xmlpullparser.end_document) {
 
   switch (event) {
 
   case xmlpullparser.start_document:
    persons = new arraylist<person>();
    break;
   case xmlpullparser.start_tag:
    if ("person".equals(pullparser.getname())) {
     int id = integer.valueof(pullparser.getattributevalue(0));
     person = new person();
     person.setid(id);
    }
    if ("name".equals(pullparser.getname())) {
     string name = pullparser.nexttext();
     person.setname(name);
    }
    if ("age".equals(pullparser.getname())) {
     int age = integer.valueof(pullparser.nexttext());
     person.setage(age);
    }
    break;
 
   case xmlpullparser.end_tag:
    if ("person".equals(pullparser.getname())) {
     persons.add(person);
     person = null;
    }
    break;
 
   }
 
   event = pullparser.next();
  }
  return persons;
 }
 
 /**
  * 保存数据到xml文件中
  * @param persons
  * @param out
  * @throws exception
  */
 public static void save(list<person> persons, outputstream out) throws exception {
  xmlserializer serializer = xml.newserializer();
  serializer.setoutput(out, "utf-8");
  serializer.startdocument("utf-8", true);
  serializer.starttag(null, "persons");
  for (person person : persons) {
   serializer.starttag(null, "person");
   serializer.attribute(null, "id", person.getid().tostring());
   serializer.starttag(null, "name");
   serializer.text(person.getname().tostring());
   serializer.endtag(null, "name");
   serializer.starttag(null, "age");
   serializer.text(person.getage().tostring());
   serializer.endtag(null, "age");
   serializer.endtag(null, "person");
  }
  serializer.endtag(null, "persons");
  serializer.enddocument();
  out.flush();
  out.close();
 }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!