今天就跟大家聊聊有關android中如何利用XPath 解析xml,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
XPath 是一門在 XML 文檔中查找信息的語言。XPath 可用來在 XML 文檔中對元素和屬性進行遍歷。
XPath 是 W3C XSLT 標準的主要元素,并且 XQuery 和 XPointer 同時被構建于 XPath 表達之上。
因此,對 XPath 的理解是很多高級 XML 應用的基礎。具體學習XPath參照http://www.php.cn/。
XPath只適合用來查詢xml的信息,對于完整的解析xml文件的建議不要使用這個方式,最好的解析xml文件應該是sax,pull這兩種方式。
我是在android 2.2系統上做的這個測試,低于2.2不知道行不行。
下面就具體說下XPath解析xml的步驟:xpathTest.xml 和android dom 解析xml方式 中的DomTest.xml一樣
1、創建InputSources
2、獲得XPathFactory實例。
3、用XPathFactory實例獲取XPath的實例
4、XPath調用evaluate()方法獲取查詢出的NodeList
private void xPathParserXml(){
//獲取XPathFactory實例
XPathFactory factory = XPathFactory.newInstance();
//用工程生成XPath實例,解析xml
XPath xpath = factory.newXPath();
//
try {
InputSource source = new InputSource(getResources().getAssets().open("xPathTest.xml"));
//第一個參數:需要查詢的節點名稱,必須要在節點前加“//”
//第二個參數:查詢的輸入源
//第三個參數:返回的類型
// NodeList nodeList = (NodeList) xpath.evaluate("//group", source, XPathConstants.NODESET);
// if(nodeList != null && nodeList.getLength() > 0){
// for(int i = 0;i < nodeList.getLength();i++){
// Node node = nodeList.item(i);
// //在這也可以得到<group>的子節點<person>。但是這樣不符合xpath的風格。
// NodeList personList = node.getChildNodes();
// Element nodeAttr =(Element)node;
// String groupName = nodeAttr.getAttribute("name");
// String num = nodeAttr.getAttribute("num");
//
// Log.e("TEST", ""+groupName+" "+num);
// }
// }
// //獲取<person>節點信息
// NodeList personList = (NodeList) xpath.evaluate("//person", source, XPathConstants.NODESET);
// if(personList != null && personList.getLength() > 0){
// for(int i = 0;i < personList.getLength();i++){
// Element node = (Element)personList.item(i);
// //在這也可以得到<person>的子節點<chinese>和<english>。
// NodeList childList = node.getChildNodes();
// String groupName = node.getAttribute("name");
// String age = node.getAttribute("age");
//
// Log.e("TEST", ""+groupName+" "+age);
// }
// }
//獲取<chinese>節點信息
NodeList chineseList = (NodeList) xpath.evaluate("//chinese", source, XPathConstants.NODESET);
if(chineseList != null && chineseList.getLength() > 0){
for(int i = 0;i < chineseList.getLength();i++){
Node node = chineseList.item(i);
String chinese = node.getTextContent();
Log.e("TEST", ""+chinese);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
注意:xpath.evaluate()不能調用兩次,報錯誤。至于原因不清楚。知道原因的請留言告知,謝謝。
對已有人提出XPath能不能查詢很大的xml文件(超過1M或),這個在理論上應該可以,只要你能解決InputSource可以讀取大容量文件問題就可以了。
看完上述內容,你們對android中如何利用XPath 解析xml有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。