XML解析Pull解析

时间:2022-07-23 20:22:25
public class MainActivity extends Activity {
private List<Book> l;
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);XmlPullParser xpp = Xml.newPullParser();try {xpp.setInput(getAssets().open("books.xml"), "utf-8");int event = xpp.getEventType();String name = "";Book b = null;int i = 0;boolean flag = true;while (flag) {switch (event) {case XmlPullParser.START_DOCUMENT:l = new ArrayList<Book>();break;case XmlPullParser.START_TAG:name = xpp.getName();if (name.equals("china")) {i = 1;}if (name.equals("foreiner")) {i = 2;}if (name.equals("book")) {b = new Book();if (i == 1) {b.setCountry("china");} if (i == 2) {b.setCountry("foreiner");}}break;case XmlPullParser.TEXT:if (name.equals("price")) {b.setPrice(xpp.getText());} else if (name.equals("name")) {b.setName(xpp.getText());} else if (name.equals("author")) {b.setAuthor(xpp.getText());} break;case XmlPullParser.END_TAG:name = xpp.getName();if (name.equals("book")) {l.add(b);}if (name.equals("china") || name.equals("foreiner")) {i = 0;}name = "";break;case XmlPullParser.END_DOCUMENT:flag = false;break;}event = xpp.next();}} catch (Exception e) {e.printStackTrace();}System.out.println(l.toString());Log.d("user", l.toString());}
}<?xml version="1.0" encoding="UTF-8"?><books><china><book><price>50</price><name>三国演义</name><author>罗贯中</author> </book> <book> <price>60</price> <name>红楼梦</name> <author>曹雪芹</author> </book><book><price>40</price> <name>水浒传</name> <author>施耐庵</author> </book></china><foreiner><book><price>50</price><name>巴黎圣母院</name><author>雨果</author> </book> <book> <price>60</price> <name>母亲</name> <author>高尔基</author> </book><book><price>40</price> <name>钢铁怎样炼成的</name> <author>列夫</author> </book></foreiner></books>