android dom 解析xml方式

黄舟
發布: 2017-02-17 15:02:21
原創
1217 人瀏覽過

首先自己建立一個xml檔案:DomTest.xml



	
		
			
				语文80
			
			
				英语89
			
		
		
			
				语文90
			
			
				英语99
			
		
	
	
		
			
				语文85
			
			
				英语95
			
		
		
			
				语文80
			
			
				英语90
			
		
	
登入後複製

解析出來的結果顯示如下圖:

下面來分析原始碼:

/**
 * 用dom方式 解析xml 文件
 * @param fileName
 */
	private String domXmlParse(String fileName) {
		String str="";
		// xml文档创建工厂
		DocumentBuilderFactory docFactory = DocumentBuilderFactory
				.newInstance();
		// xml文档创建实例
		DocumentBuilder docBuilder;
		// xml文档
		Document doc = null;
		InputStream inStream = null;
		try {
			docBuilder = docFactory.newDocumentBuilder();
			// 从assets文件夹下获取文件 转换成输入流
			inStream = this.getResources().getAssets().open(fileName);
			doc = docBuilder.parse(inStream);
			// 获取xml跟元素
			Element rootEle = doc.getDocumentElement();
			// 二级父元素的list列表
			NodeList groupNode = rootEle.getElementsByTagName("group");
			// NodeList childNode = rootEle.getElementsByTagName("person");
			// 遍历Classe下所有的group
			for (int i = 0; i < groupNode.getLength(); i++) {

				Element groupEle = (Element) groupNode.item(i);
				String groupName = groupEle.getAttribute("name");
				String num = groupEle.getAttribute("num");
				str =str+"name ="+groupName+" num = "+num+"\n";
				
				Log.e("xml", "name = " + groupName + "  num = " + num);

//				NodeList personNode = groupNode.item(i).getChildNodes();
				NodeList personNode = groupEle.getElementsByTagName("person");
				// 遍历group下的所有person
				for (int j = 0; j < personNode.getLength(); j++) {
					Element personEle = (Element) personNode.item(j);
					String name = personEle.getAttribute("name");
					String age = personEle.getAttribute("age");
					str =str+"personName ="+name+" personAge = "+age+"\n";
					
					Log.e("xml", "name = " + name + "   age = " + age);

					Element chineseEle = (Element) personEle
							.getElementsByTagName("chinese").item(0);
					Element englistEle = (Element) personEle
							.getElementsByTagName("english").item(0);
					String chinese = chineseEle.getFirstChild().getNodeValue();
					String english = englistEle.getFirstChild().getNodeValue();
					str =str+"chinese = "+chinese+" english = "+english+"\n";
					
					Log.e("xml", "chinese = " + chinese + "   english = "
							+ english);
				}
			}

		} catch (ParserConfigurationException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		return str;
	}
登入後複製

為 XML 文件的已解析版本定義了一組介面。解析器讀入整個文檔,然後建立一個駐留記憶體的樹結構,然後程式碼就可以使用 DOM 介面來操作這個樹結構。優點:整個文檔樹在記憶體中,方便操作;支援刪除、修改、重新排列等多種功能;缺點:將整個文件調入記憶體(包括無用的節點),浪費時間和空間;使用場合:一旦解析了文件也需多次存取這些資料;硬體資源充足(記憶體、CPU)。 


 以上就是android dom 解析xml方式 的內容,並有更多相關內容請關注PHP中文網(m.sbmmt.com)!

 

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!