关闭

XmlPullParser

101人阅读 评论(0) 收藏 举报
public class MainActivity extends Activity {
private List<Book> l;
@Override
protected 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>
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7587次
    • 积分:270
    • 等级:
    • 排名:千里之外
    • 原创:20篇
    • 转载:3篇
    • 译文:0篇
    • 评论:1条
    文章存档
    最新评论