`
vbtboy
  • 浏览: 46809 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

xpath小例子

阅读更多
package com.myapp.utils;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class XpathStudy {
public static void main(String args[]) {
try {
File file = new File(
"D:\\workspace\\MyHome\\src\\com\\myapp\\utils\\test.xml");
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
// NodeList nodeList = document.getElementsByTagName("book");
//   for(int i=0;i<nodeList.getLength();i++){
// System.out.println(document.getElementsByTagName("title").item(i).getFirstChild().getNodeValue());
// System.out.println(document.getElementsByTagName("price").item(i).getFirstChild().getNodeValue());
//   }
  XPathFactory xpathFactory =XPathFactory.newInstance();
  XPath xpath = xpathFactory.newXPath();
  XPathExpression expression = xpath.compile("bookstore//book/title[@lang='guo']/text()");
  Object result = expression.evaluate(document,XPathConstants.NODESET);
  NodeList nodeList = (NodeList)result;
  for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getNodeValue());
}

} catch (Exception e) {
e.printStackTrace();
}
}
}


另附js方法实现
var xmlDoc = new ActiveXObject("Microsoft.xmldom");
xmlDoc.async="false";
xmlDoc.load("test.xml");
alert(xmlDoc.selectNodes("bookstore/book/title[@lang='guo']")[0].text);


text.xml

<?xml version="1.0" encoding="gbk"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
<book>
<title lang="guo">郭德纲相声选</title>
<price>$0.01</price>
</book>
</bookstore>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics