Java XPath示例教程

时间:2020-02-23 14:37:01  来源:igfitidea点击:

欢迎使用Java XPath示例教程。
XPath提供了定义XML文档一部分的语法。
XPath表达式是一种查询语言,用于根据查询字符串选择XML文档的一部分。
使用XPath表达式,我们可以在任何xml文档中找到满足查询字符串的节点。

Java XPath

javax.xml.xpath包在Java中提供了XPath支持。
为了创建XPathExpression,XPath API提供了工厂方法。

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile(XPATH_EXPRESSION_STRING);
Object result = expr.evaluate(Object item, QName returnType);

Java XPath支持的返回类型在XPathConstants类中定义。

  • XPathConstants.STRING
  • XPathConstants.NUMBER
  • XPathConstants.BOOLEAN
  • XPathConstants.NODE
  • XPathConstants.NODESET

Java XPath示例

在此Java XPath示例教程中,我们有以下示例xml文件。

employees.xml

<?xml version="1.0" encoding="UTF-8"?>
<Employees>
	<Employee id="1">
		<age>29</age>
		<name>hyman</name>
		<gender>Male</gender>
		<role>Java Developer</role>
	</Employee>
	<Employee id="2">
		<age>35</age>
		<name>Lisa</name>
		<gender>Female</gender>
		<role>CEO</role>
	</Employee>
	<Employee id="3">
		<age>40</age>
		<name>Tom</name>
		<gender>Male</gender>
		<role>Manager</role>
	</Employee>
	<Employee id="4">
		<age>25</age>
		<name>Meghna</name>
		<gender>Female</gender>
		<role>Manager</role>
	</Employee>
</Employees>

我们将在Java XPath示例程序中实现以下功能。

  • 该函数将返回Employee Name作为输入ID。

  • 返回年龄大于输入年龄的雇员姓名列表。

  • 返回女员工姓名列表。

这是Java XPath示例程序的最终实现类。

XPathQueryExample.java

package com.theitroad.xml;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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;
import org.xml.sax.SAXException;

public class XPathQueryExample {

  public static void main(String[] args) {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware(true);
      DocumentBuilder builder;
      Document doc = null;
      try {
          builder = factory.newDocumentBuilder();
          doc = builder.parse("/Users/hyman/employees.xml");

          //Create XPathFactory object
          XPathFactory xpathFactory = XPathFactory.newInstance();

          //Create XPath object
          XPath xpath = xpathFactory.newXPath();

          String name = getEmployeeNameById(doc, xpath, 4);
          System.out.println("Employee Name with ID 4: " + name);

          List<String> names = getEmployeeNameWithAge(doc, xpath, 30);
          System.out.println("Employees with 'age>30' are:" + Arrays.toString(names.toArray()));

          List<String> femaleEmps = getFemaleEmployeesName(doc, xpath);
          System.out.println("Female Employees names are:" +
                  Arrays.toString(femaleEmps.toArray()));

      } catch (ParserConfigurationException | SAXException | IOException e) {
          e.printStackTrace();
      }

  }

  private static List<String> getFemaleEmployeesName(Document doc, XPath xpath) {
      List<String> list = new ArrayList<>();
      try {
          //create XPathExpression object
          XPathExpression expr =
              xpath.compile("/Employees/Employee[gender='Female']/name/text()");
          //evaluate expression result on XML document
          NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
          for (int i = 0; i < nodes.getLength(); i++)
              list.add(nodes.item(i).getNodeValue());
      } catch (XPathExpressionException e) {
          e.printStackTrace();
      }
      return list;
  }

  private static List<String> getEmployeeNameWithAge(Document doc, XPath xpath, int age) {
      List<String> list = new ArrayList<>();
      try {
          XPathExpression expr =
              xpath.compile("/Employees/Employee[age>" + age + "]/name/text()");
          NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
          for (int i = 0; i < nodes.getLength(); i++)
              list.add(nodes.item(i).getNodeValue());
      } catch (XPathExpressionException e) {
          e.printStackTrace();
      }
      return list;
  }

  private static String getEmployeeNameById(Document doc, XPath xpath, int id) {
      String name = null;
      try {
          XPathExpression expr =
              xpath.compile("/Employees/Employee[@id='" + id + "']/name/text()");
          name = (String) expr.evaluate(doc, XPathConstants.STRING);
      } catch (XPathExpressionException e) {
          e.printStackTrace();
      }

      return name;
  }

}

当我们在Java XPath示例程序上方运行时,将导致以下输出。

Employee Name with ID 4: Meghna
Employees with 'age>30' are:[Lisa, Tom]
Female Employees names are:[Lisa, Meghna]

注意,前几行将XML文件读取为Document。
然后,我们将在所有方法中重用Document和XPath对象。
上面的程序显示了NODESET和STRING作为结果对象的示例。