android之xml数据解析(DOM)
16lz
2021-01-25
DOM解析是把整个需要解析的xml文件暂存在内存中。
需要解析的XML文档:
<? xmlversion="1.0"encoding="UTF-8" ?>< persons >
< person id ="23" >
< name >lee </ name >
< age >30 </ age >
</ person >
< person id ="20" >
< name >leo </ name >
< age >24 </ age >
</ person >
</persons>
使用DOM方式解析的java代码:
packagexml;importjava.io.IOException;
importjavax.xml.parsers.DocumentBuilder;
importjavax.xml.parsers.DocumentBuilderFactory;
importjavax.xml.parsers.ParserConfigurationException;
importorg.w3c.dom.Document;
importorg.w3c.dom.Element;
importorg.w3c.dom.Node;
importorg.w3c.dom.NodeList;
importorg.xml.sax.SAXException;
public classDOMForXml{
public static voidmain(String[]args){
// 使用DocumentBuilderFactory工厂创建DocumentBuilder对象
DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance();
try{
// 生成DocumentBuilder
DocumentBuilderbuilder=factory.newDocumentBuilder();
// 调用完这句后XML文档解析完成,暂存在内存中
Documentdocument=builder.parse("test.xml");
// 获得根元素
Elementroot=document.getDocumentElement();
// 匹配结点,返回结点集
NodeListpersonNodes=root.getElementsByTagName("person");
for( inti=0;i<personNodes.getLength();i++){
// 遍历结点集
ElementpersonElement=(Element)personNodes.item(i);
// 获得结点上的属性
Stringid=personElement.getAttribute("id");
// 输出
System.out.println("id:"+id);
// 获得该节点下面的子节点
NodeListpersonChilds=personElement.getChildNodes();
// 遍历子结点
for( intj=0;j<personChilds.getLength();j++){
// 判断当前结点是否是元素类型结点
if(personChilds.item(j).getNodeType()==Node.ELEMENT_NODE){
ElementchildElement=(Element)personChilds.item(j);
// 判断当前结点
if(childElement.getNodeName().equals("name")){
// 获得当前结点对应的值
System.out.println("name:"+childElement.getFirstChild().getNodeValue());
} else if(childElement.getNodeName().equals("age")){
System.out.println("age:"+childElement.getFirstChild().getNodeValue());
}
}
}
}
} catch(ParserConfigurationExceptione){
// TODOAuto-generatedcatchblock
e.printStackTrace();
} catch(SAXExceptione){
// TODOAuto-generatedcatchblock
e.printStackTrace();
} catch(IOExceptione){
// TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
更多相关文章
- 手把手带你搭建 Elasticsearch 集群
- Android读取SIM联系人信息
- Android(安卓)ALSA audio 的一些问题
- 32、详解Android(安卓)shape的使用方法
- cocos2dx 3.3final 编译Android(安卓)平台
- Ubuntu 安装 ADT和SDK
- Android网络访问与数据解析
- RK3288_Android7.1接eDP屏休眠之后led状态灯没有亮红色
- Android之Sax解析xml(4)