1. 介绍
在Android系统中很多信息及配置文件都是以xml格式存储的,Android系统也提供SAX和DOM两种方式来解析XML文件,下面介绍其中比较简单的DOM方式。
2. 例程
1) 功能
解析xml文件内容,并显示在程序界面上
2) 关键字
Android, xml, dom, 解析
3) 可从此处下载可独立运行的代码
http://download.csdn.net/detail/xieyan0811/4117455
4) 核心代码及说明
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 内容
<?xml version="1.0" encoding="utf-8" ?>
<menu>
<submenutitle="test1">
<item desc="item1" pos="012" />
<item desc="item2" pos="123" />
</submenu>
<submenutitle="test2">
<item desc="item3" pos="234" />
<item desc="item4" pos="456" />
</submenu>
<submenu title="test3">
<item desc="item5" pos="567" />
<item desc="item6" pos="678" />
<item desc="item7" pos="789" />
</submenu>
</menu>
3. 参考
1) SAX教程:http://www.2cto.com/kf/201101/81739.html
(转载请注明出处)