最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android利用Dom對XML進(jìn)行增刪改查操作詳解

 更新時間:2018年01月15日 11:51:42   作者:栗子醬油餅  
使用DOM進(jìn)行增刪改查,這個是DOM的優(yōu)勢所在,其實代碼很簡單,不需要過多的解釋,下面這篇文章主要給大家介紹了關(guān)于Android利用Dom對XML進(jìn)行增刪改查操作的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。

1. 概述

平常我們一般是使用JSON與服務(wù)器做數(shù)據(jù)通信,JSON的話,直接用GSON或者其他庫去解析很簡單。但是,其他有些服務(wù)器會返回XML格式的文件,這時候就需要去讀取XML文件了。

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

2. Dom解析

DOM解析器在解析XML文檔時,會把文檔中的所有元素,按照其出現(xiàn)的層次關(guān)系,解析成一個個Node對象(節(jié)點)。再形象點,就是一棵樹,多節(jié)點的樹,稱為Dom樹。

Node對象提供了一系列常量來代表結(jié)點的類型,當(dāng)開發(fā)人員獲得某個Node類型后,就可以把Node節(jié)點轉(zhuǎn)換成相應(yīng)節(jié)點對象(Node的子類對象),以便于調(diào)用其特有的方法。

Node對象提供了相應(yīng)的方法去獲得它的父結(jié)點或子結(jié)點。編程人員通過這些方法就可以讀取整個XML文檔的內(nèi)容、或添加、修改、刪除XML文檔的內(nèi)容.

3. Dom解析代碼示例

代碼如下:

/**
 * DOM解析
 * 把文檔中的所有元素,按照其出現(xiàn)的層次關(guān)系,解析成一個個Node對象(節(jié)點)。
 * 缺點是消耗大量的內(nèi)存。
 * @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的相關(guān)信息。

xmlVersion,代表的是xml的版本

children,子節(jié)點,是Element,對應(yīng)上面的,是最外層的package

Element,是xml的最外層的結(jié)點,由document.getDocumentElement() 得到 。

Node,結(jié)點。何為結(jié)點?其實就是一個<abc></abc>的一個結(jié)點信息,存儲著一些,結(jié)點本身的屬性,和其結(jié)點下的子結(jié)點等等。

//得到最外層的節(jié)點
Element element = document.getDocumentElement();
//得到節(jié)點的屬性
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
}
//得到子節(jié)點列表
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
 Node node = nodeList.item(i);
 //每個node下面,也可能有node,和,node的屬性,獲取都如上所示
}

Node,每個node里面的屬性,也是node,每個node下的子節(jié)點node也是一個一個node

 //節(jié)點的屬性
 Node node = namedNodeMap.item(i);
 node.getNodeName();//key
 node.getTextContent();//value
 node.getNodeType();//node type
 //節(jié)點下的子節(jié)點
 NodeList nodeList = element.getChildNodes();
 for (int i = 0; i < nodeList.getLength(); i++) {
 Node node = nodeList.item(i);
 //每個node下面,也可能有node,和,node的屬性,獲取都如上所示
 }

4.1 實踐一下,查找

在android系統(tǒng)里面,安裝的每一個app,其信息都被存到一個xml里面:/data/system/packages.xml,可以通過root去查看里面的內(nèi)容,大概如下(其實上面的例子就是從這個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>
 //一堆的權(quán)限
 <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>

而現(xiàn)在有個需求,查找是否有app:com.xx.xx,也就是查找xml中的package節(jié)點中的name屬性值有沒有此包名。
我們先封裝一下代碼吧:

public class XmlUtils {
 /**
 * DOM解析
 * 把文檔中的所有元素,按照其出現(xiàn)的層次關(guān)系,解析成一個個Node對象(節(jié)點)。
 * 缺點是消耗大量的內(nèi)存。
 * @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節(jié)點
  if (node.getNodeName() != null && node.getNodeName().equals("package")) {
  //提取參數(shù)列表
  NamedNodeMap namedNodeMap = node.getAttributes();
  if (namedNodeMap != null && namedNodeMap.getLength()>0) {
  //判斷參數(shù)中是否有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")) {
   //進(jìn)行您的操作
   }
  }
  }
  }
  }
 }
 }
 });

注意,要做好判空。有可能很多node不存在參數(shù),或者沒有子節(jié)點。

5. 增刪改

當(dāng)加載xml到內(nèi)存中后,你可以對document進(jìn)行修改

增加

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. 保存

在內(nèi)存中修改好的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 {
 //將內(nèi)存中的Dom保存到文件
 TransformerFactory tFactory = TransformerFactory.newInstance();
 Transformer transformer = tFactory.newTransformer();
 //設(shè)置輸出的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解析
 * 把文檔中的所有元素,按照其出現(xiàn)的層次關(guān)系,解析成一個個Node對象(節(jié)點)。
 * 缺點是消耗大量的內(nèi)存。
 * @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 {
 //將內(nèi)存中的Dom保存到文件
 TransformerFactory tFactory = TransformerFactory.newInstance();
 Transformer transformer = tFactory.newTransformer();
 //設(shè)置輸出的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));
 }
}

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論

梨树县| 红原县| 海盐县| 池州市| 盐源县| 巍山| 德江县| 体育| 辽宁省| 衡南县| 老河口市| 柞水县| 海兴县| 嘉鱼县| 剑阁县| 贵德县| 杂多县| 泸定县| 名山县| 岳阳县| 闸北区| 左云县| 浦江县| 惠州市| 宜丰县| 舒兰市| 河津市| 寻甸| 镇康县| 沙坪坝区| 封开县| 顺平县| 綦江县| 娱乐| 博爱县| 阿尔山市| 泾川县| 伊川县| 花莲市| 衡东县| 黄大仙区|