自己学习使用,轻喷
***解析xml文件:
通过类加载器获得文件person.xml的输入流:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("person.xml");
PaserService.getPersons(is);
===============PaserService================
public class PaserService { public static ArrayList<Person> getPersons(InputStream inputStream) throws Exception{ ArrayList<Person> persons = null; Person person = null; XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser paser = factory.newPullParser(); paser.setInput(inputStream, "UTF-8"); int eventType = paser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT: persons = new ArrayList<Person>(); break; case XmlPullParser.START_TAG: if ("person".equals(paser.getName())) { person = new Person(); person.setPersonid(paser.getAttributeValue(0)); //获得节点属性的第一个值,第二个值就为数组的1 } else if ("name".equals(paser.getName())){ person.setPersonname(paser.nextText()); //获得节点里面的数据 } else if ("phone".equals(paser.getName())){ person.setPersonnum(paser.nextText()); } break; case XmlPullParser.END_TAG: if ("person".equals(paser.getName())) { persons.add(person); person = null; } break; default: break; } eventType = paser.next(); //将节点的循环继续往下 } return persons; } }
***把值按xml格式写入某个xml中:
记得在Androidmanifest.xml中加入写入sdcard的权限
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File file = new File(Environment.getExternalStorageDirectory(), "persons.xml"); //存储到sd卡中
FileOutputStream fos = new FileOutputStream(file);
PaserService.writeXml(fos, persons);
====writeXml====
public static void writeXml(OutputStream os, ArrayList<Person> persons) throws Exception{ XmlSerializer serializer = Xml.newSerializer(); serializer.setOutput(os, "UTF-8"); serializer.startDocument("UTF-8", true); serializer.startTag(null, "persons"); for (Person person : persons) { serializer.startTag(null, "person"); serializer.attribute(null, "id", person.getPersonid()); serializer.startTag(null, "name"); serializer.text(person.getPersonname()); serializer.endTag(null, "name"); serializer.startTag(null, "phone"); serializer.text(person.getPersonnum()); serializer.endTag(null, "phone"); serializer.endTag(null, "person"); } serializer.endTag(null, "persons"); serializer.endDocument(); os.flush(); os.close(); }