package cn.xml.bean; 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 android.util.Log; import android.util.Xml; public class PullParseXml { public static List<Book> readXml(InputStream instream)throws Exception { List<Book> books=null; Book book=null; //获取XmlPullParser对象 XmlPullParser parser=Xml.newPullParser(); //设置要解析的xml文件输入流,并且采用UTF-8编码 parser.setInput(instream, "UTF-8"); int event=parser.getEventType(); while(event!=XmlPullParser.END_DOCUMENT) { switch(event) { case XmlPullParser.START_DOCUMENT : books=new ArrayList<Book>(); Log.i("BBB", "########welcome you!"); break; case XmlPullParser.START_TAG : if("book".equals(parser.getName())) { book=new Book(); int id=Integer.valueOf(parser.getAttributeValue(0)); book.setId(id); }else if("bookName".equals(parser.getName())){ String bookName=parser.nextText(); book.setBookName(bookName); }else if("author".equals(parser.getName())){ String author=parser.nextText(); book.setAuthor(author); }else if("price".equals(parser.getName())){ double price=Double.valueOf(parser.nextText()); book.setPrice(price); } break; case XmlPullParser.END_TAG : if("book".equals(parser.getName())) { books.add(book); } } event=parser.next(); } instream.close(); return books; } //新建一个xml文件 public static void writeXml(List<Book> books,OutputStream outStream) throws Exception { XmlSerializer serializer=Xml.newSerializer(); serializer.setOutput(outStream,"UTF-8"); serializer.startDocument("UTF-8",true); serializer.startTag(null, "books"); for(Book book : books) { serializer.startTag(null,"book"); serializer.attribute(null, "id", book.getId()+""); serializer.startTag(null,"bookName"); serializer.text(book.getBookName()); serializer.endTag(null,"bookName"); serializer.startTag(null,"author"); serializer.text(book.getAuthor()); serializer.endTag(null,"author"); serializer.startTag(null,"price"); serializer.text(book.getPrice()+""); serializer.endTag(null,"price"); serializer.endTag(null,"book"); } serializer.endTag(null, "books"); serializer.endDocument(); outStream.flush();//强制缓冲区中的数据被写出 outStream.close(); } }
xml文件
牛博文 13:42:25 <?xml version="1.0" encoding="UTF-8"?> <books> <book id="321"> <bookName>Android基础</bookName> <author>张三</author> <price>2.58</price> </book> <book id="322"> <bookName>Android游戏开发</bookName> <author>李四</author> <price>1.2</price> </book> <book id="323"> <bookName>三个男人和一女人的故事</bookName> <author>王五</author> <price>24.5</price> </book> </books>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。