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 XML数据解析简单示例全部内容,希望文章能够帮你解决Android XML数据解析简单示例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)