1. 概述

平常我们一般是使用JSON与服务器做数据通信,JSON的话,直接用GSON或者其他库去解析很简单。但是,其他有些服务器会返回XML格式的文件,这时候就需要去读取XML文件了。

XML的解析有三种方式,在Android中提供了三种解析XML的方式:DOM(Document Objrect Model) , SAX(Simple API XML) ,以及Android推荐的Pull解析方式,他们也各有弊端,而这里来看看使用DOM的方式。

2. Dom解析

DOM解析器在解析XML文档时,会把文档中的所有元素,按照其出现的层次关系,解析成一个个Node对象(节点)。再形象点,就是一棵树,多节点的树,称为Dom树。

Node对象提供了一系列常量来代表结点的类型,当开发人员获得某个Node类型后,就可以把Node节点转换成相应节点对象(Node的子类对象),以便于调用其特有的方法。

Node对象提供了相应的方法去获得它的父结点或子结点。编程人员通过这些方法就可以读取整个XML文档的内容、或添加、修改、删除XML文档的内容.

3. Dom解析代码示例

代码如下:

/** * DOM解析 * 把文档中的所有元素,按照其出现的层次关系,解析成一个个Node对象(节点)。 * 缺点是消耗大量的内存。 * @param xmlFilePath 文件 * @return Document */public static Document loadWithDom(String xmlFilePath) { try { File file = new File(xmlFilePath); if (!file.exists()) { throw new RuntimeException("not find file:" + xmlFilePath); } else { InputStream inputStream = new FileInputStream(file); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); try { inputStream.close(); } catch (Exception e) { e.printStackTrace(); } return document; } } catch (ParserConfigurationException | IOException | SAXException e) { return null; } }

上面的方法是同步的,最终返回的是一个 Document 对象。

4. 查找

自定义一个稍微简单的XML:

<?xml version="1.0" encoding="utf-8" standalone='yes'?>                

使用上面的代码去解析,Document如下:


Documnet,it is the root of the document tree, and provides the primary access to the document's data. 就是整个xml的root,通过它可以获取到xml的相关信息。

xmlVersion,代表的是xml的版本

children,子节点,是Element,对应上面的,是最外层的package

Element,是xml的最外层的结点,由document.getDocumentElement() 得到 。

Node,结点。何为结点?其实就是一个的一个结点信息,存储着一些,结点本身的属性,和其结点下的子结点等等。

//得到最外层的节点Element element = document.getDocumentElement();//得到节点的属性NamedNodeMap namedNodeMap = element.getAttributes();//便利属性并log输出for (int i = 0; i < namedNodeMap.getLength(); i++) { Node node = namedNodeMap.item(i); node.getNodeName();//key node.getTextContent();//value node.getNodeType();//node type}//得到子节点列表NodeList nodeList = element.getChildNodes();for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); //每个node下面,也可能有node,和,node的属性,获取都如上所示}

Node,每个node里面的属性,也是node,每个node下的子节点node也是一个一个node

 //节点的属性 Node node = namedNodeMap.item(i); node.getNodeName();//key node.getTextContent();//value node.getNodeType();//node type //节点下的子节点 NodeList nodeList = element.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); //每个node下面,也可能有node,和,node的属性,获取都如上所示 }

4.1 实践一下,查找

在android系统里面,安装的每一个app,其信息都被存到一个xml里面:/data/system/packages.xml,可以通过root去查看里面的内容,大概如下(其实上面的例子就是从这个xml文件copy来的):

<?xml version="1.0" encoding="utf-8" standalone='yes'?>     //一堆的权限   //一堆的app       

而现在有个需求,查找是否有app:com.xx.xx,也就是查找xml中的package节点中的name属性值有没有此包名。
我们先封装一下代码吧:

public class XmlUtils { /** * DOM解析 * 把文档中的所有元素,按照其出现的层次关系,解析成一个个Node对象(节点)。 * 缺点是消耗大量的内存。 * @param xmlFilePath 文件 * @return Document */ public static Document loadWithDom(String xmlFilePath) { try { File file = new File(xmlFilePath); if (!file.exists()) { throw new RuntimeException("not find file:" + xmlFilePath); } else { InputStream inputStream = new FileInputStream(file); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); try {  inputStream.close(); } catch (Exception e) {  e.printStackTrace(); } return document; } } catch (ParserConfigurationException | IOException | SAXException e) { return null; } } public static Observable loadWithDomRx(String xmlFilePath) { return Observable.just(loadWithDom(xmlFilePath)); }}

封装好之后,就可以写代码,如下:

//加载文件XmlUtils.loadWithDomRx("/sdcard/Test.xml") .subscribe(document -> { //判断是否加载到文件 if (document!=null && document.getDocumentElement()!=null) { //判断有无node NodeList nodeList = document.getDocumentElement().getChildNodes(); if (nodeList != null) {  //遍历node list  for (int i = 0; i < nodeList.getLength(); i++) {  Node node = nodeList.item(i);  //判断是否是package节点  if (node.getNodeName() != null && node.getNodeName().equals("package")) {  //提取参数列表  NamedNodeMap namedNodeMap = node.getAttributes();  if (namedNodeMap != null && namedNodeMap.getLength()>0) {  //判断参数中是否有com.xx.xx  Node n = namedNodeMap.item(0);  if (n.getNodeName()!=null && n.getNodeName().equals("name")) {   if (n.getTextContent()!=null && n.getTextContent().equals("com.xx.xx")) {   //进行您的操作   }  }  }  }  } } } });

注意,要做好判空。有可能很多node不存在参数,或者没有子节点。

5. 增删改

当加载xml到内存中后,你可以对document进行修改

增加

Element element = document.createElement("New Node");element.setAttribute("key1","value1");element.setAttribute("key2","value2");node.appendChild(element);

删除

//注意的是,你需要先找出这个node对象,因为api没有提供直接remove index 的node的方法。element.removeChild(node);node1.removeChild(node2);

修改

//找到具体的node,或者,elemnet,修改:node.setNodeValue("edit key");node.setTextContent("edit value");

6. 保存

在内存中修改好的document对象,直接保存为新的xml文件,代码如下:

/** * 保存修改后的Doc * http://blog.csdn.net/franksun1991/article/details/41869521 * @param doc doc * @param saveXmlFilePath 路径 * @return 是否成功 */public static boolean saveXmlWithDom(Document doc,String saveXmlFilePath) { if (doc==null || saveXmlFilePath==null || saveXmlFilePath.isEmpty()) return false; try { //将内存中的Dom保存到文件 TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); //设置输出的xml的格式,utf-8 transformer.setOutputProperty("encoding", "utf-8"); transformer.setOutputProperty("version",doc.getXmlVersion()); DOMSource source = new DOMSource(doc); //打开输出流 File file = new File(saveXmlFilePath); if (!file.exists()) Log.i("XmlUtils","saveXmlWithDom,createNewFile:"+file.createNewFile()); OutputStream outputStream = new FileOutputStream(file); //xml的存放位置 StreamResult src = new StreamResult(outputStream); transformer.transform(source, src); return true; } catch (Exception e) { e.printStackTrace(); return false; }}

7. 附上工具类

/** * 
 * author: Chestnut * blog : http://www.jianshu.com/u/a0206b5f4526 * time : 2018/1/10 17:14 * desc : XML解析工具类 * thanks To: * 1. [Android解析XML的三种方式] http://blog.csdn.net/d_shadow/article/details/55253586 * 2. [Android几种解析XML方式的比较] http://blog.csdn.net/isee361820238/article/details/52371342 * 3. [android xml 解析 修改] http://blog.csdn.net/i_lovefish/article/details/39476051 * 4. [android 对xml文件的pull解析,生成xml ,对xml文件的增删] http://blog.csdn.net/jamsm/article/details/52205800 * dependent on: * update log: * 
*/public class XmlUtils { /** * DOM解析 * 把文档中的所有元素,按照其出现的层次关系,解析成一个个Node对象(节点)。 * 缺点是消耗大量的内存。 * @param xmlFilePath 文件 * @return Document */ public static Document loadWithDom(String xmlFilePath) { try { File file = new File(xmlFilePath); if (!file.exists()) { throw new RuntimeException("not find file:" + xmlFilePath); } else { InputStream inputStream = new FileInputStream(file); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(inputStream); try { inputStream.close(); } catch (Exception e) { e.printStackTrace(); } return document; } } catch (ParserConfigurationException | IOException | SAXException e) { return null; } } public static Observable loadWithDomRx(String xmlFilePath) { return Observable.just(loadWithDom(xmlFilePath)); } /** * 保存修改后的Doc * http://blog.csdn.net/franksun1991/article/details/41869521 * @param doc doc * @param saveXmlFilePath 路径 * @return 是否成功 */ public static boolean saveXmlWithDom(Document doc,String saveXmlFilePath) { if (doc==null || saveXmlFilePath==null || saveXmlFilePath.isEmpty()) return false; try { //将内存中的Dom保存到文件 TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); //设置输出的xml的格式,utf-8 transformer.setOutputProperty("encoding", "utf-8"); transformer.setOutputProperty("version",doc.getXmlVersion()); DOMSource source = new DOMSource(doc); //打开输出流 File file = new File(saveXmlFilePath); if (!file.exists()) Log.i("XmlUtils","saveXmlWithDom,createNewFile:"+file.createNewFile()); OutputStream outputStream = new FileOutputStream(file); //xml的存放位置 StreamResult src = new StreamResult(outputStream); transformer.transform(source, src); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public static Observable saveXmlWithDomRx(Document doc,String saveXmlFilePath) { return Observable.just(saveXmlWithDom(doc, saveXmlFilePath)); }}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

更多相关文章

  1. 资源之关于资源文件夹介绍
  2. Android(安卓)程序的主要组成部分 和 Manifest 文件
  3. Android对Linux内核的改动你知道多少?
  4. 深入探讨Android----必不可少的高级功能
  5. Android高性能文件类MemoryFile
  6. JIN学习一、Android使用已有C/C++代码、第三方SO库的方法
  7. Android中自定义组合控件
  8. Android(安卓)进阶解密:init 进程启动过程
  9. s5p4418 Android(安卓)4.4.2 驱动层 HAL层 服务层 应用层 开发流

随机推荐

  1. RK3288 android7.1.2 android studio 用
  2. android MIME文件类型
  3. android程序入口
  4. Android(安卓)SDK 更新问题
  5. Android获取当前时间的android.text.form
  6. android的ListView点击item使item展开的
  7. 使用Chronometer 间断计时
  8. android ViewPager自动轮播时控制切换速
  9. Android(安卓)一些鲜为人知的方法
  10. Android(安卓)Design Support Library 使