什么是Xpath路径表达式
- Xpath路径表达式是XML文档中查询数据的语言
- 掌握XPath可以极大的提高提取数据时的开发效率
- 学习XPath本质就是掌握各种形式的表达式的使用技巧
Xpath基本表达式
- 最常用的基本表达式
有如下示例:
- Xpath谓语表达式
在基本表达式之上增加了其他的选择条件:
Jaxen
jaxen是一个java编写的开源的XPath库。这里适应多种不同的对象模型,包括DOM, XOM, dom4j和JDOM, Dom4j的底层依赖Jaxen实现Xpath查询,所以在使用Xpath进行XML查询的时候,我们需要首先进行Jaxen的安装。百度搜索jaxen,下载jar包,将其导入到Reference Libraries中。
下面是使用dom4j进行xpath操作。xml文件为这篇博客里的xml文件
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class XPathTensor {
public void xpath(String xpathExp) {
String file = "。。。。。。。。。。。。。";
SAXReader reader = new SAXReader();
try {
Document document = reader.read(file);
List<Node> nodes = document.selectNodes(xpathExp);
for (Node node : nodes) {
Element emp = (Element) node;
System.out.println(emp.elementText("name"));
System.out.println(emp.elementText("age"));
System.out.println(emp.elementText("salary"));
System.out.println("=======================");
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
XPathTensor xt = new XPathTensor();
xt.xpath("/hr/employee");
xt.xpath("//employee");
xt.xpath("//employee[salary<8000]");
}
}