Android XML数据解析简单示例
1、创建xml数据
在android工程目录中res/目录下创建raw文件夹,在raw文件夹内创建data.xml。
<?xml version="1.0" encoding="utf-8"?>
<data>
<class>
<c studentnum="1">android</c>
<c studentnum="2">iphone</c>
</class>
</data>
2、xml解析代码
import java.io.ioexception;
import java.io.inputstream;
import javax.xml.parsers.documentbuilder;
import javax.xml.parsers.documentbuilderfactory;
import javax.xml.parsers.parserconfigurationexception;
import org.w3c.dom.document;
import org.w3c.dom.namednodemap;
import org.w3c.dom.node;
import org.w3c.dom.nodelist;
import org.xml.sax.saxexception;
import android.os.bundle;
import android.app.activity;
public class mainactivity extends activity {
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
inputstream is = getresources().openrawresource(r.raw.data);
try {
byte[] bytes = new byte[is.available()];
is.read();
string xmlstr = new string(bytes,"utf-8");
is.reset();
system.out.println(xmlstr);
documentbuilder builder = documentbuilderfactory.newinstance().newdocumentbuilder();
document doc = builder.parse(is);
node node = doc.getfirstchild();
system.out.println("第一个子节点"+node.getnodename());
nodelist list = doc.getelementsbytagname("c");
namednodemap map;
for(int i = 0; i < list.getlength(); i++)
{
node = list.item(i);
map = node.getattributes();
system.out.println(node.gettextcontent()+" studentnum "+map.getnameditem("studentnum").getnodevalue());
}
} catch (ioexception e) {
// todo auto-generated catch block
e.printstacktrace();
} catch (parserconfigurationexception e) {
// todo auto-generated catch block
e.printstacktrace();
} catch (saxexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
下一篇: Android游戏源码分享之2048