Android XmlPullParser 解析xml

Android 解析Xml 的方式有多种,SAX、DOM、Pull 都可以实现,这里使用的是其中的一种.
下面的代码主要是在IntentService 里面解析一个xml 白名单的.主要是记录一下,时间长了容易忘记.

public class NameListServices extends IntentService {
	private final static String TAG = "NameListServices";

	private List<AppInfo> infos = new ArrayList<AppInfo>();
	public NameListServices() {
		super("NameListServices");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Log.i(TAG, "onHandleIntent");
		if(intent != null) {
			String uri = intent.getStringExtra("uri");
			InputStream is = null;
			if(uri != null) {
				try {
					is = getContentResolver().openInputStream(Uri.fromFile(new File(uri)));
					readXml(is);
					//updateInfoToDB();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					if(is != null) {
						try {
							is.close();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
				}
			}
		}
	}

	private void readXml(InputStream is) {
		Log.i(TAG, "readXml");
		try {
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(is, "UTF-8");
			int eventType = parser.getEventType();

			AppInfo appInfo ;
			while(eventType != XmlPullParser.END_DOCUMENT) {
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					String name = parser.getName();
					if(name != null && name.trim().equals("AppInfo")) {
						String pkg = parser.getAttributeValue(null,"pkg");
						String type = parser.getAttributeValue(null,"type");
						appInfo = new AppInfo(pkg, type);
						Log.i(TAG, "appInfo:" + appInfo);
						infos.add(appInfo);
					}
					break;
				case XmlPullParser.END_TAG:
					break;

				default:
					break;
				}
				eventType = parser.next();
			}
		}catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <AppInfo pkg = "com.android.settings" type="projection" />
    <AppInfo pkg = "cn.nubia.gallery3d" type="projection" />
    <AppInfo pkg = "cn.nubia.contacts" type="hook" />
    <AppInfo pkg = "cn.nubia.browser" type="hook" />
    <AppInfo pkg = "cn.nubia.neoshare" type="projection_hook" />
    <AppInfo pkg = "cn.nubia.mms" type="projection_hook" />
</resources>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值