Android利用Dom对XML进行增删改查操作详解

时间:2019-04-12
本文章向大家介绍Android利用Dom对XML进行增删改查操作详解,主要包括Android利用Dom对XML进行增删改查操作详解使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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'?>
<packages key1="value1" key2="value2">
 <last-platform-version internal="22" external="22" fingerprint="honeybot/H1f/H1f:5.1.1/LMY47V/huiyu01091530:userdebug/test-keys"/>
 <database-version internal="3" external="3"/>
 <permission-trees/>
 <permissions>
 <item name="android.permission.SET_SCREEN_COMPATIBILITY" package="android" protection="2"/>
 <item name="android.permission.MEDIA_CONTENT_CONTROL" package="android" protection="18"/>
 <item name="android.permission.DELETE_PACKAGES" package="android" protection="18"/>
 <item name="com.android.voicemail.permission.ADD_VOICEMAIL" package="android" protection="1"/>
 </permissions>
 <package name="com.android.providers.downloads" codePath="/system/priv-app/DownloadProvider" nativeLibraryPath="/system/priv-app/DownloadProvider/lib" flags="1074282053" ft="15f9e785498" it="15f9e785498" ut="15f9e785498" version="22" sharedUserId="10002">
 <sigs count="1">
 <cert index="1"/>
 </sigs>
 <proper-signing-keyset identifier="2"/>
 <signing-keyset identifier="2"/>
 </package>
</packages>

使用上面的代码去解析,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,结点。何为结点?其实就是一个<abc></abc>的一个结点信息,存储着一些,结点本身的属性,和其结点下的子结点等等。

//得到最外层的节点
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'?>
<packages key1="value1" key2="value2">
 <last-platform-version internal="22" external="22" fingerprint="honeybot/H1f/H1f:5.1.1/LMY47V/huiyu01091530:userdebug/test-keys"/>
 <database-version internal="3" external="3"/>
 <permission-trees/>
 <permissions>
 //一堆的权限
 <item name="android.permission.SET_SCREEN_COMPATIBILITY" package="android" protection="2"/>
 </permissions>
 //一堆的app
 <package name="com.android.providers.downloads" codePath="/system/priv-app/DownloadProvider" nativeLibraryPath="/system/priv-app/DownloadProvider/lib" flags="1074282053" ft="15f9e785498" it="15f9e785498" ut="15f9e785498" version="22" sharedUserId="10002">
 <sigs count="1">
 <cert index="1"/>
 </sigs>
 <proper-signing-keyset identifier="2"/>
 <signing-keyset identifier="2"/>
 </package>
</packages>

而现在有个需求,查找是否有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<Document> 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. 附上工具类

/**
 * <pre>
 * 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:
 * </pre>
 */
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<Document> 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<Boolean> saveXmlWithDomRx(Document doc,String saveXmlFilePath) {
 return Observable.just(saveXmlWithDom(doc, saveXmlFilePath));
 }
}

总结

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