您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。