XPath 是一门在 XML 文档中查找信息的言语。XPath 可用来在 XML 文档中对元素和属性举行遍历。
XPath 是 W3C XSLT 规范的重要元素,而且 XQuery 和 XPointer 同时被构建于 XPath 表达之上。
因而,对 XPath 的明白是许多高等 XML 运用的基本。详细进修XPath参照http://www.ki4.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的内容,更多相关内容请关注ki4网(www.ki4.cn)!