栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

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

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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解析代码示例

代码如下:


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:



 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

使用上面的代码去解析,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来的):



 
 
 
 
 //一堆的权限
 
 
 //一堆的app
 
 
 
 
 
 
 

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

public class XmlUtils {
 
 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文件,代码如下:


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. 附上工具类

public class XmlUtils {
 
 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));
 }
 
 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));
 }
}

总结

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

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

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号