栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 前沿技术 > 人工智能 > NLP

android dom 解析xml方式

NLP 更新时间:发布时间: 百科书网 趣学号
首先自己创建一个xml文件:DomTest.xml

语文80英语89语文90英语99语文85英语95语文80英语90

解析出来的结果显示如下图:

下面来分析源代码:

private String domXmlParse(String fileName) {String str="";// xml文档创建工厂documentBuilderFactory docFactory = documentBuilderFactory.newInstance();// xml文档创建实例documentBuilder docBuilder;// xml文档document doc = null;InputStream inStream = null;try {docBuilder = docFactory.newdocumentBuilder();// 从assets文件夹下获取文件 转换成输入流inStream = this.getResources().getAssets().open(fileName);doc = docBuilder.parse(inStream);// 获取xml跟元素Element rootEle = doc.getdocumentElement();// 二级父元素的list列表NodeList groupNode = rootEle.getElementsByTagName("group");// NodeList childNode = rootEle.getElementsByTagName("person");// 遍历Classe下所有的groupfor (int i = 0; i < groupNode.getLength(); i++) {Element groupEle = (Element) groupNode.item(i);String groupName = groupEle.getAttribute("name");String num = groupEle.getAttribute("num");str =str+"name ="+groupName+" num = "+num+"n";Log.e("xml", "name = " + groupName + "  num = " + num);//NodeList personNode = groupNode.item(i).getChildNodes();NodeList personNode = groupEle.getElementsByTagName("person");// 遍历group下的所有personfor (int j = 0; j < personNode.getLength(); j++) {Element personEle = (Element) personNode.item(j);String name = personEle.getAttribute("name");String age = personEle.getAttribute("age");str =str+"personName ="+name+" personAge = "+age+"n";Log.e("xml", "name = " + name + "   age = " + age);Element chineseEle = (Element) personEle.getElementsByTagName("chinese").item(0);Element englistEle = (Element) personEle.getElementsByTagName("english").item(0);String chinese = chineseEle.getFirstChild().getNodevalue();String english = englistEle.getFirstChild().getNodevalue();str =str+"chinese = "+chinese+" english = "+english+"n";Log.e("xml", "chinese = " + chinese + "   english = "+ english);}}} catch (ParserConfigurationException e1) {e1.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (SAXException e) {e.printStackTrace();}return str;}

为 XML 文档的已解析版本定义了一组接口。解析器读入整个文档,然后构建一个驻留内存的树结构,然后代码就可以使用 DOM 接口来操作这个树结构。优点:整个文档树在内存中,便于操作;支持删除、修改、重新排列等多种功能;缺点:将整个文档调入内存(包括无用的节点),浪费时间和空间;使用场合:一旦解析了文档还需多次访问这些数据;硬件资源充足(内存、CPU)。


以上就是android dom 解析xml方式 的内容,更多相关内容请关注PHP中文网(www.iotsi.net)!

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/794883.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号