# Java xpath 示例 – 在 xml 文件上求值 xpath

> 原文： [https://howtodoinjava.com/xml/evaluate-xpath-on-dom/](https://howtodoinjava.com/xml/evaluate-xpath-on-dom/)

**Java xpath 示例**读取 XML 文件并解析为 DOM 对象，然后**求值`org.w3c.dom.Document`对象**上的 xpath 并以`String`或`NodeList`的形式获取结果。

## 1\. Java 求值 xml 文件上的 xpath

1.  创建`Document` DOM 对象`javax.xml.parsers.DocumentBuilder`对象。
2.  从[`XPathFactory`](https://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html)创建[`XPath`](https://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPath.html)。
3.  使用[`xpath.evaluate('expression', dom, resultType)`](https://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPath.html#evaluate-java.lang.String-org.xml.sax.InputSource-)获取结果 HTML。

```java
package com.howtodoinjava.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";

		//Get DOM
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document xml = db.parse(xmlFile);

        //Get XPath 
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();

        //Get first match
        String name = (String) xpath.evaluate("/employees/employee/firstName", xml, XPathConstants.STRING);

        System.out.println(name);	//Lokesh

        //Get all matches
        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
        }
    }
}    

```

程序输出：

```java
Lokesh
1
2

```

## 2\. XML 文件

输入的 xml 文件为：

```java
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees>
    <employee id="1">
        <firstName>Lokesh</firstName>
        <lastName>Gupta</lastName>
        <department>
            <id>101</id>
            <name>IT</name>
        </department>
    </employee>
    <employee id="2">
        <firstName>Brian</firstName>
        <lastName>Schultz</lastName>
        <department>
            <id>102</id>
            <name>HR</name>
        </department>
    </employee>
</employees>

```

学习愉快！

阅读更多：

[字符串中的 Java xpath 示例](https://howtodoinjava.com/xml/evaluate-xpath-on-xml-string/)

[Java xpath 教程](https://howtodoinjava.com/xml/how-to-work-with-xpaths-in-java-with-examples/)

[如何在 Java 中使用 xpath 获取 xml 中的属性值](https://howtodoinjava.com/xml/xpath-attribute-evaluate/)