www. On IT Road .com
在 Java 中计算xml文件上的xpath 示例
- 创建
DocumentDOM 对象javax.xml.parsers.DocumentBuilder对象。 - 从
XPathFactory创建XPath。 - 使用
xpath.evaluate('expression', dom, resultType)获取结果 HTML。
package com.onitroad.demo;
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.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class XPathExample
{
public static void main(String[] args) throws Exception
{
String xmlFile = "employees.xml";
// 获取DOM
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document xml = db.parse(xmlFile);
// 获取 XPath
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
// 获取第1个匹配项
String name = (String) xpath.evaluate("/employees/employee/firstName", xml, XPathConstants.STRING);
System.out.println(name); //JackLi
// 获取所有的匹配项
NodeList nodes = (NodeList) xpath.evaluate("/employees/employee/@id", xml, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue()); //1 2
}
}
}
测试使用的XML文件
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees>
<employee id="1">
<firstName>JackLi</firstName>
<lastName>Gupta</lastName>
<department>
<id>101</id>
<name>IT</name>
</department>
</employee>
<employee id="2">
<firstName>BobRobert</firstName>
<lastName>Schultz</lastName>
<department>
<id>102</id>
<name>HR</name>
</department>
</employee>
</employees>
日期:2020-09-17 00:10:13 来源:oir作者:oir
