关闭

pull解析复杂xml文件

99人阅读 评论(0) 收藏 举报
分类:

xml文件

<?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>

解析

// 解析数据
	private void pullparsexml() {
		XmlPullParser parser = Xml.newPullParser();
		try {
			parser.setInput(getAssets().open("books.xml"), "utf-8");
			int event = parser.getEventType();
			flag = true;
			while (flag) {
				switch (event) {
				case XmlPullParser.START_DOCUMENT:
					china = new ArrayList<Books>();
					foreiner = new ArrayList<Books>();
					break;
				case XmlPullParser.START_TAG:
					tagname = parser.getName();
					if (tagname.equals("china")) {
						tag = 0;
					} else if (tagname.equals("foreiner")) {
						tag = 1;
					} else if (tagname.equals("book")) {
						book = new Books();
					}

					break;
				case XmlPullParser.TEXT:
					if (tagname.equals("price")) {
						book.setPrice(parser.getText());
					} else if (tagname.equals("name")) {
						book.setName(parser.getText());
					} else if (tagname.equals("author")) {
						book.setAuthor(parser.getText());
					}
					break;
				case XmlPullParser.END_TAG:
					tagname = parser.getName();
					if (tagname.equals("book")) {
						if (tag == 0) {
							china.add(book);
						} else if (tag == 1) {
							foreiner.add(book);
						}
					}
					tagname = "";
					break;
				case XmlPullParser.END_DOCUMENT:
					flag = false;
					break;

				default:
					break;
				}
				event = parser.next();
			}
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}


0
0

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