Android利用Dom對(duì)XML進(jìn)行增刪改查操作詳解
1. 概述
平常我們一般是使用JSON與服務(wù)器做數(shù)據(jù)通信,JSON的話,直接用GSON或者其他庫(kù)去解析很簡(jiǎn)單。但是,其他有些服務(wù)器會(huì)返回XML格式的文件,這時(shí)候就需要去讀取XML文件了。
XML的解析有三種方式,在Android中提供了三種解析XML的方式:DOM(Document Objrect Model)
, SAX(Simple API XML)
,以及Android推薦的Pull解析方式,他們也各有弊端,而這里來(lái)看看使用DOM的方式。
2. Dom解析
DOM解析器在解析XML文檔時(shí),會(huì)把文檔中的所有元素,按照其出現(xiàn)的層次關(guān)系,解析成一個(gè)個(gè)Node對(duì)象(節(jié)點(diǎn))。再形象點(diǎn),就是一棵樹(shù),多節(jié)點(diǎn)的樹(shù),稱(chēng)為Dom樹(shù)。
Node對(duì)象提供了一系列常量來(lái)代表結(jié)點(diǎn)的類(lèi)型,當(dāng)開(kāi)發(fā)人員獲得某個(gè)Node類(lèi)型后,就可以把Node節(jié)點(diǎn)轉(zhuǎn)換成相應(yīng)節(jié)點(diǎn)對(duì)象(Node的子類(lèi)對(duì)象),以便于調(diào)用其特有的方法。
Node對(duì)象提供了相應(yīng)的方法去獲得它的父結(jié)點(diǎn)或子結(jié)點(diǎn)。編程人員通過(guò)這些方法就可以讀取整個(gè)XML文檔的內(nèi)容、或添加、修改、刪除XML文檔的內(nèi)容.
3. Dom解析代碼示例
代碼如下:
/** * DOM解析 * 把文檔中的所有元素,按照其出現(xiàn)的層次關(guān)系,解析成一個(gè)個(gè)Node對(duì)象(節(jié)點(diǎn))。 * 缺點(diǎn)是消耗大量的內(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; } }
上面的方法是同步的,最終返回的是一個(gè) Document 對(duì)象。
4. 查找
自定義一個(gè)稍微簡(jiǎn)單的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. 就是整個(gè)xml的root,通過(guò)它可以獲取到xml的相關(guān)信息。
xmlVersion,代表的是xml的版本
children,子節(jié)點(diǎn),是Element,對(duì)應(yīng)上面的,是最外層的package
Element,是xml的最外層的結(jié)點(diǎn),由document.getDocumentElement()
得到 。
Node,結(jié)點(diǎn)。何為結(jié)點(diǎn)?其實(shí)就是一個(gè)<abc></abc>的一個(gè)結(jié)點(diǎn)信息,存儲(chǔ)著一些,結(jié)點(diǎn)本身的屬性,和其結(jié)點(diǎn)下的子結(jié)點(diǎn)等等。
//得到最外層的節(jié)點(diǎn) Element element = document.getDocumentElement(); //得到節(jié)點(diǎn)的屬性 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é)點(diǎn)列表 NodeList nodeList = element.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); //每個(gè)node下面,也可能有node,和,node的屬性,獲取都如上所示 }
Node,每個(gè)node里面的屬性,也是node,每個(gè)node下的子節(jié)點(diǎn)node也是一個(gè)一個(gè)node
//節(jié)點(diǎn)的屬性 Node node = namedNodeMap.item(i); node.getNodeName();//key node.getTextContent();//value node.getNodeType();//node type //節(jié)點(diǎn)下的子節(jié)點(diǎn) NodeList nodeList = element.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); //每個(gè)node下面,也可能有node,和,node的屬性,獲取都如上所示 }
4.1 實(shí)踐一下,查找
在android系統(tǒng)里面,安裝的每一個(gè)app,其信息都被存到一個(gè)xml里面:/data/system/packages.xml,可以通過(guò)root去查看里面的內(nèi)容,大概如下(其實(shí)上面的例子就是從這個(gè)xml文件copy來(lái)的):
<?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)在有個(gè)需求,查找是否有app:com.xx.xx,也就是查找xml中的package節(jié)點(diǎn)中的name屬性值有沒(méi)有此包名。
我們先封裝一下代碼吧:
public class XmlUtils { /** * DOM解析 * 把文檔中的所有元素,按照其出現(xiàn)的層次關(guān)系,解析成一個(gè)個(gè)Node對(duì)象(節(jié)點(diǎn))。 * 缺點(diǎn)是消耗大量的內(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)); } }
封裝好之后,就可以寫(xiě)代碼,如下:
//加載文件 XmlUtils.loadWithDomRx("/sdcard/Test.xml") .subscribe(document -> { //判斷是否加載到文件 if (document!=null && document.getDocumentElement()!=null) { //判斷有無(wú)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é)點(diǎn) 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ù),或者沒(méi)有子節(jié)點(diǎn)。
5. 增刪改
當(dāng)加載xml到內(nèi)存中后,你可以對(duì)document進(jìn)行修改
增加
Element element = document.createElement("New Node"); element.setAttribute("key1","value1"); element.setAttribute("key2","value2"); node.appendChild(element);
刪除
//注意的是,你需要先找出這個(gè)node對(duì)象,因?yàn)閍pi沒(méi)有提供直接remove index 的node的方法。 element.removeChild(node); node1.removeChild(node2);
修改
//找到具體的node,或者,elemnet,修改: node.setNodeValue("edit key"); node.setTextContent("edit value");
6. 保存
在內(nèi)存中修改好的document對(duì)象,直接保存為新的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); //打開(kāi)輸出流 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. 附上工具類(lèi)
/** * <pre> * author: Chestnut * blog : http://www.jianshu.com/u/a0206b5f4526 * time : 2018/1/10 17:14 * desc : XML解析工具類(lèi) * 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 對(duì)xml文件的pull解析,生成xml ,對(duì)xml文件的增刪] http://blog.csdn.net/jamsm/article/details/52205800 * dependent on: * update log: * </pre> */ public class XmlUtils { /** * DOM解析 * 把文檔中的所有元素,按照其出現(xiàn)的層次關(guān)系,解析成一個(gè)個(gè)Node對(duì)象(節(jié)點(diǎn))。 * 缺點(diǎn)是消耗大量的內(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); //打開(kāi)輸出流 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é)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
Android編程之監(jiān)聽(tīng)器用法實(shí)例分析
這篇文章主要介紹了Android編程之監(jiān)聽(tīng)器用法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Android監(jiān)聽(tīng)器的功能及針對(duì)短信的監(jiān)聽(tīng)與響應(yīng)操作技巧,需要的朋友可以參考下2016-01-01超好看的下拉刷新動(dòng)畫(huà)Android代碼實(shí)現(xiàn)
超好看的下拉刷新動(dòng)畫(huà)Android代碼實(shí)現(xiàn),效果簡(jiǎn)單大方,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-01-01Android SD卡上文件操作及記錄日志操作實(shí)例分析
這篇文章主要介紹了Android SD卡上文件操作及記錄日志操作的方法,涉及Android針對(duì)SD卡與文件操作的相關(guān)技巧,需要的朋友可以參考下2016-01-01android使用TextView實(shí)現(xiàn)跑馬燈效果
這篇文章主要為大家詳細(xì)介紹了android使用TextView實(shí)現(xiàn)跑馬燈效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-05-05Android開(kāi)發(fā)之保存圖片到相冊(cè)的三種方法詳解
這篇文章主要介紹了Android開(kāi)發(fā)實(shí)現(xiàn)的保存圖片到相冊(cè)功能的三種方法,文中的示例代碼講解詳細(xì),有一定的參考價(jià)值,感興趣的可以了解一下2022-04-04Android構(gòu)建Material Design應(yīng)用詳解
這篇文章主要為大家詳細(xì)介紹了Android構(gòu)建Material Design應(yīng)用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10AndroidManifest.xml <uses-feature>和<uses-permisstio
這篇文章主要介紹了AndroidManifest.xml <uses-feature>和<uses-permisstion>分析及比較的相關(guān)資料,需要的朋友可以參考下2017-06-06