标签:
解析xml的方式有很多,可以用dom,sax解析,但是在android平台上最常用是Pull解析,下面是简单的示例
<?xmlversion="1.0" encoding="UTF-8"?> <persons> <person id=“18"> <name>allen</name> <age>36</age> </person> <person id=“28"> <name>james</name> <age>25</age> </person> </persons>
public class Person { private Integer id; private String name; private Short age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Short getAge() { return age; } public void setAge(Short age) { this.age = age; } }生成xml文件
public static String writeXML(List<Person> persons, Writer writer){ XmlSerializer serializer = Xml.newSerializer(); try { serializer.setOutput(writer); serializer.startDocument("UTF-8", true); //第一个参数为命名空间,如果不使用命名空间,可以设置为null serializer.startTag("", "persons"); for (Person person : persons){ serializer.startTag("", "person"); serializer.attribute("", "id", person.getId().toString()); serializer.startTag("", "name"); serializer.text(person.getName()); serializer.endTag("", "name"); serializer.startTag("", "age"); serializer.text(person.getAge().toString()); serializer.endTag("", "age"); serializer.endTag("", "person"); } serializer.endTag("", "persons"); serializer.endDocument(); return writer.toString(); } catch (Exception e) { e.printStackTrace(); } return null; }
public static List<Person> readXML(InputStream inStream) { XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(inStream, "UTF-8"); int eventType = parser.getEventType(); Person currentPerson = null; List<Person> persons = null; while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT://文档开始事件,可以进行数据初始化处理 persons = new ArrayList<Person>(); break; case XmlPullParser.START_TAG://开始元素事件 String name = parser.getName(); if (name.equalsIgnoreCase("person")) { currentPerson = new Person(); currentPerson.setId(new Integer(parser.getAttributeValue(null, "id"))); } else if (currentPerson != null) { if (name.equalsIgnoreCase("name")) { currentPerson.setName(parser.nextText());// 如果后面是Text节点,即返回它的值 } else if (name.equalsIgnoreCase("age")) { currentPerson.setAge(new Short(parser.nextText())); } } break; case XmlPullParser.END_TAG://结束元素事件 if (parser.getName().equalsIgnoreCase("person") && currentPerson != null) { persons.add(currentPerson); currentPerson = null; } break; } eventType = parser.next(); } inStream.close(); return persons; } catch (Exception e) { e.printStackTrace(); } return null; }
,
标签:
原文地址:http://blog.csdn.net/qq_21413973/article/details/51345877