Android 使用 DOM 方式解析 XML

#移动开发 #Android

1.介绍
在 Android 系统中很多信息及配置文件都是以 xml 格式存储的,Android 系统也提供 SAX 和 DOM 两种方式来解析 XML 文件,下面介绍其中比较简单的 DOM 方式。

2.例程

  1. 功能
    解析 xml 文件内容,并显示在程序界面上

  2. 关键字
    Android, xml, dom, 解析

  3. 可从此处下载可独立运行的代码
    [http://download.csdn.net/detail/xieyan0811/4117455

](http://download.csdn.net/detail/xieyan0811/4117455)

  1. 核心代码及说明

package com.demo.xml;


import android.app.Activity;

import android.os.Bundle;

import android.widget.TextView;

import android.widget.LinearLayout;

import android.util.Log;


import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import java.io.IOException;

import java.io.InputStream;


public class MyXmlActivity extends Activity {

private String TAG ="demo";


@Override

public voidonCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

parseXml();

}


private voidparseXml() {

int i, j;

TextViewtext;

LinearLayoutlinear = new LinearLayout(this);

linear.setOrientation(LinearLayout.VERTICAL);


DocumentBuilderFactorydocFactory = DocumentBuilderFactory

.newInstance();

DocumentBuilderdocBuilder;

Document doc= null;

InputStreaminStream = null;

try {

docBuilder= docFactory.newDocumentBuilder();

inStream= this.getResources().getAssets().open("test.xml");

doc= docBuilder.parse(inStream);

ElementrootEle = doc.getDocumentElement();

NodeListquestionNode = rootEle.getElementsByTagName("submenu");

intsubCount = questionNode.getLength();

for(i = 0; i < subCount; i++) {

ElementsubEle = (Element) questionNode.item(i);

StringsubTitle = subEle.getAttribute("title");

Log.e(TAG,"title = " + subTitle);

text= new TextView(this);

text.setText(subTitle);

linear.addView(text);


NodeListitemNode = subEle.getElementsByTagName("item");

intitemCount = itemNode.getLength();

for(j = 0; j < itemCount; j++) {

ElementoptionEle = (Element) itemNode.item(j);

Stringdesc = optionEle.getAttribute("desc");

Stringpos = optionEle.getAttribute("pos");

Log.e(TAG,"desc = " + desc + ", pos = " + pos);

text= new TextView(this);

text.setText(desc+ ", " + pos);

linear.addView(text);

}

}

} catch(ParserConfigurationException e1) {

e1.printStackTrace();

} catch(IOException e) {

e.printStackTrace();

} catch(Exception e) {

e.printStackTrace();

}

setContentView(linear);

}

};


// xml 内容

** **

**

**

** <submenutitle="test1"> **

** **

** **

** **

** <submenutitle="test2"> **

** **

** **

**
**

** **

** **

** **

** **

**

**

3.参考

  1. SAX 教程:http://www.2cto.com/kf/201101/81739.html

(转载请注明出处)