android解析XML文件

本文介绍两种从config.xml中读取数据的方法:DOM方式和Pull方式。DOM方式通过DocumentBuilderFactory创建Document对象并解析XML文件;Pull方式使用XmlPullParser解析XML文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于config.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="server_api">http://www.phpwind.net/</string>
	<string name="app_name">phpwind</string>
	<string name="app_label">phpwind</string>
</resources>

1.  DOM方式 

public void getByDOM() {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(getResources().getAssets().open("xmlfile/config.xml"));
			Element element = document.getDocumentElement();
			NodeList nodes = element.getElementsByTagName("string");
			for (int i = 0; i < nodes.getLength(); i++) {
				Element node = (Element) nodes.item(i);
				Log.i(TAG, "name:" + node.getAttribute("name") + ", value:" + node.getFirstChild().getNodeValue());
				// node.getTextContent();
			}
		} catch (SAXException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		}
	}


2.  Pull方式

public void getByPull() {
		XmlPullParser xml = null;
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			xml = factory.newPullParser();
			xml.setInput(getAssets().open("xmlfile/config.xml"), "utf-8");
			int tagType = xml.next();
			while (tagType != XmlPullParser.END_DOCUMENT) {
				if (tagType == XmlPullParser.START_TAG && xml.getName().equals("string")) {
					Log.i(TAG, xml.getAttributeValue("", "name"));
					xml.next();
					Log.i(TAG, "----" + xml.getText());
				}
				tagType = xml.next();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值