标签:
利用XmlSerializer和XmlPullParser对xml文件进行读写操作
下面是XmlSerializer在手机内存中写入xml文件的内容:
public void writeXML(){ File file =new File(this.getFilesDir(), "test.xml"); XmlSerializer s=Xml.newSerializer(); try { FileOutputStream fos = new FileOutputStream(file); s.setOutput(fos, "utf-8"); s.startDocument("utf-8", null); s.startTag(null, "persons"); for(int i=0;i<10;i++){ s.startTag(null, "p"); s.startTag(null, "name"); s.text("啊"+String.valueOf(i)); s.endTag(null, "name"); s.startTag(null, "age"); s.text(String.valueOf(10+i)); s.endTag(null, "age"); s.endTag(null, "p"); } s.endTag(null, "persons"); s.endDocument(); fos.flush(); fos.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
下面是XmlPullParser在手机内存中读取xml文件的内容:
public List<Person> readXML(){ list = null; Person p=null; File file =new File(this.getFilesDir(), "test.xml"); XmlPullParser parser=Xml.newPullParser(); try { FileInputStream fis=new FileInputStream(file); parser.setInput(fis, "utf-8"); int eventType=parser.getEventType(); while(eventType!=XmlPullParser.END_DOCUMENT){ String tagName=parser.getName(); switch (eventType) { case XmlPullParser.START_TAG: if("persons".equals(tagName)){ list=new ArrayList<Person>(); }else if("p".equals(tagName)){ p=new Person(); }else if("name".equals(tagName)){ p.setName(parser.nextText()); }else if("age".equals(tagName)){ p.setAge(Integer.parseInt(parser.nextText())); } break; case XmlPullParser.END_TAG: if("p".equals(tagName)){ list.add(p); } break; default: break; } eventType=parser.next(); } fis.close(); } catch (Exception e) { e.printStackTrace(); } return list; }
标签:
原文地址:http://www.cnblogs.com/zzqhfuf/p/4607469.html