之路教程 https://onitr oad .com

Java计算 xpath 表达式

package com.onitroad.demo;
import java.util.ArrayList;
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.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 
	{
		// 从XML获取DOM节点
		String fileName= "employees.xml";
		Document document = getDocument(fileName);

		String xpathExpression = "";

		// 获取所有employee的id
		xpathExpression = "/employees/employee/@id";
		System.out.println( evaluateXPath(document, xpathExpression) );

		// 获取HR部门的所有employee的id
		xpathExpression = "/employees/employee[department/name='HR']/@id";
		System.out.println( evaluateXPath(document, xpathExpression) );

		// 获取'JackLi'的id
		xpathExpression = "/employees/employee[firstName='JackLi']/@id";
		System.out.println( evaluateXPath(document, xpathExpression) );

		// 获取大于5的employee
		xpathExpression = "/employees/employee/@id[. > 5]";
		System.out.println( evaluateXPath(document, xpathExpression) );

		// 获取id包含1的employee
		xpathExpression = "/employees/employee[contains(@id,'1')]/firstName/text()";
		System.out.println( evaluateXPath(document, xpathExpression) );

		// 获取id包含1的employee
		xpathExpression = "descendant-or-self::*[contains(@id,'1')]/firstName/text()";
		System.out.println( evaluateXPath(document, xpathExpression) );
	}

	private static List<String> evaluateXPath(Document document, String xpathExpression) throws Exception 
	{
		// Create XPathFactory object
		XPathFactory xpathFactory = XPathFactory.newInstance();

		// Create XPath object
		XPath xpath = xpathFactory.newXPath();
		List<String> values = new ArrayList<>();
		try 
		{
			// Create XPathExpression object
			XPathExpression expr = xpath.compile(xpathExpression);

			// Evaluate expression result on XML document
			NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

			for (int i = 0; i < nodes.getLength(); i++) {
				values.add(nodes.item(i).getNodeValue());
			}

		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return values;
	}
	private static Document getDocument(String fileName) throws Exception 
	{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(fileName);
		return doc;
	}
}

3. 模型类

@XmlRootElement(name="employees")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employees implements Serializable
{
	private static final long serialVersionUID = 1L;

	@XmlElement(name="employee")
	private List<Employee> employees;
	public List<Employee> getEmployees() {
		if(employees == null) {
			employees = new ArrayList<Employee>();
		}
		return employees;
	}
	public void setEmployees(List<Employee> employees) {
		this.employees = employees;
	}
	@Override
	public String toString() {
		return "Employees [employees=" + employees + "]";
	}
}
@XmlRootElement(name="employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee implements Serializable {
	private static final long serialVersionUID = 1L;
	@XmlAttribute
	private Integer id;
	private String firstName;
	private String lastName;
	private Department department;
	public Employee() {
		super();
	}
	public Employee(int id, String fName, String lName, Department department) {
		super();
		this.id = id;
		this.firstName = fName;
		this.lastName = lName;
		this.department = department;
	}
	//Setters and Getters
	@Override
	public String toString() {
		return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", department=" + department + "]";
	}
}
@XmlRootElement(name="department")
@XmlAccessorType(XmlAccessType.FIELD)
public class Department implements Serializable {

	private static final long serialVersionUID = 1L;

	Integer id;
	String name;

	public Department() {
		super();
	}
	public Department(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	//Setters and Getters
	@Override
	public String toString() {
		return "Department [id=" + id + ", name=" + name + "]";
	}
}
Java XML XPath 查询示例

Java 如何通过 xpath 表达式 从 XML 文档中提取信息。

XPath 查询示例

测试 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>
    <employee id="3">
        <firstName>JackLi</firstName>
        <lastName>Kolenchisky</lastName>
        <department>
            <id>103</id>
            <name>FINANCE</name>
        </department>
    </employee>
    <employee id="4">
        <firstName>cherry</firstName>
        <lastName>Jain</lastName>
        <department>
            <id>104</id>
            <name>HR</name>
        </department>
    </employee>
    <employee id="5">
        <firstName>Tomm</firstName>
        <lastName>Beckham</lastName>
        <department>
            <id>105</id>
            <name>DEVOPS</name>
        </department>
    </employee>
    <employee id="6">
        <firstName>Virat</firstName>
        <lastName>Kohli</lastName>
        <department>
            <id>106</id>
            <name>DEVOPS</name>
        </department>
    </employee>
    <employee id="7">
        <firstName>John</firstName>
        <lastName>Wick</lastName>
        <department>
            <id>107</id>
            <name>IT</name>
        </department>
    </employee>
    <employee id="8">
        <firstName>Mike</firstName>
        <lastName>Anderson</lastName>
        <department>
            <id>108</id>
            <name>HR</name>
        </department>
    </employee>
    <employee id="9">
        <firstName>Bob</firstName>
        <lastName>Sponge</lastName>
        <department>
            <id>109</id>
            <name>FINANCE</name>
        </department>
    </employee>
    <employee id="10">
        <firstName>Gary</firstName>
        <lastName>Kasporov</lastName>
        <department>
            <id>110</id>
            <name>IT</name>
        </department>
    </employee>
</employees>
日期:2020-09-17 00:10:14 来源:oir作者:oir