Android利用Dom對XML進(jìn)行增刪改查操作詳解
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)文章
Android編程實現(xiàn)隱藏狀態(tài)欄及測試Activity是否活動的方法
這篇文章主要介紹了Android編程實現(xiàn)隱藏狀態(tài)欄及測試Activity是否活動的方法,涉及Android界面布局設(shè)置及Activity狀態(tài)操作的相關(guān)技巧,需要的朋友可以參考下2016-10-10
Android自定義View實現(xiàn)字母導(dǎo)航欄的代碼
這篇文章主要介紹了Android自定義View實現(xiàn)字母導(dǎo)航欄的實例代碼,代碼簡單易懂,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-09-09
Android 使用SharePerference判斷是否為第一次登陸的實現(xiàn)代碼
很多app中在第一次安裝登陸時會有引導(dǎo)歡迎界面,第二次打開時就不再顯示引導(dǎo)頁面。這個怎么實現(xiàn)呢?下面小編給大家介紹下使用SharePerference判斷是否為第一次登陸的實現(xiàn)代碼,需要的的朋友參考下吧2017-03-03
Android手機(jī)內(nèi)存中文件的讀寫方法小結(jié)
這篇文章主要介紹了Android手機(jī)內(nèi)存中文件的讀寫方法,實例總結(jié)了Android針對文件讀寫操作的相關(guān)技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04
Android自定義View仿QQ等級天數(shù)進(jìn)度
這篇文章主要為大家詳細(xì)介紹了Android自定義View仿QQ等級天數(shù)進(jìn)度效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-07-07
Android Toolbar應(yīng)用欄使用方法簡介
App中應(yīng)用欄是十分常見的,通常應(yīng)用欄會顯示當(dāng)前頁面的標(biāo)題,還有一些操作按鈕,例如返回、搜索、掃碼等。本文介紹如何通過Toolbar實現(xiàn)應(yīng)用欄2022-12-12
Android音視頻開發(fā)之MediaPlayer使用教程
Android多媒體框架支持播放提供了MediaPlayerAPI,可以通過MediaPlayer來實現(xiàn)媒體文件播放。可以說MediaPlayer是非常方便使用的多媒體播放器。本文將詳細(xì)講解MediaPlayer的使用,需要的可以參考一下2022-04-04
Android仿QQ滑動彈出菜單標(biāo)記已讀、未讀消息
這篇文章主要介紹了Android仿QQ滑動彈出菜單標(biāo)記已讀、未讀消息的相關(guān)資料,需要的朋友可以參考下2016-01-01

