在 Java 中使用 xpath 查找具有属性值的 xml 元素

位置:首页>文章>详情   分类: Java教程 > 编程技术   阅读(298)   2023-06-26 07:54:18

如何使用 xpath 在 xml 中获取属性值的简单示例在爪哇。我们将学习获取信息以匹配属性值范围内的属性值xpath attribute contains() 等等。

1. XPath属性表达式

1.1.输入 XML 文件

首先查看我们将读取的 XML 文件,然后使用 xpath 查询 从中获取信息。

<?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>
    <employee id="3">
        <firstName>Alex</firstName>
        <lastName>Kolenchisky</lastName>
        <department>
            <id>103</id>
            <name>FINANCE</name>
        </department>
    </employee>
    <employee id="4">
        <firstName>Amit</firstName>
        <lastName>Jain</lastName>
        <department>
            <id>104</id>
            <name>HR</name>
        </department>
    </employee>
    <employee id="5">
        <firstName>David</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>

1.2. XPath 属性表达式示例

现在看一些如何构建 xpath 以获取基于属性的信息的示例。

<正文>

描述 XPath 结果
获取所有员工id <代码>/employees/员工/@id [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
获取HR部门所有员工id /employees/employee[部门/名称='HR']/@id [2, 4, 8]
获取'Alex'的员工id /employees/employee[firstName='亚历克斯']/@id [3]
获取大于5的员工id /employees/employee/@id[. > 5] [6, 7, 8, 9, 10]
获取id包含'1'的员工 /employees/employee[包含(@id,'1')]/firstName/text() [洛克什,加里]
获取id为1的员工 后裔或自我::*[contains(@id,'1')]/firstName/text() [洛克什,加里]

2. Java 示例使用 xpath 查找具有属性值的 xml 元素

让我们看一下用于评估上述 xpath 表达式以选择具有特定属性值的节点的代码。

2.1. XPath 评估示例

在 java 中评估 xpath,您需要执行以下步骤:

  • 将 XML 文件读入 org.w3c.dom.Document
  • 创建 XPathFactory 及其 newInstance() 静态方法。
  • 获取 XPath 来自 XPathFactory 的实例。此对象提供对 xpath 评估环境和表达式的访问。
  • 创建 xpath 表达式字符串。将 xpath 字符串转换为 XPathExpression 对象使用 xpath.compile() 方法。
  • 根据第一步创建的文档实例评估 xpath。它将返回文档中的 DOM 节点列表。
  • 迭代节点并使用 getNodeValue() 方法获取测试值。

XPath 表达式不是线程安全的。应用程序有责任确保在任何给定时间不从多个线程使用一个 XPathExpression 对象,并且在调用 evaluate 方法时,应用程序不得递归调用 evaluate 方法。< /p>

package com.cundage.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 
	{
		//Get DOM Node for XML
		String fileName= "employees.xml";
		Document document = getDocument(fileName);
		
		String xpathExpression = "";
			
		/*******Get attribute values using xpath******/
		
		//Get all employee ids
		xpathExpression = "/employees/employee/@id";
		System.out.println( evaluateXPath(document, xpathExpression) );
		
		//Get all employee ids in HR department
		xpathExpression = "/employees/employee[department/name='HR']/@id";
		System.out.println( evaluateXPath(document, xpathExpression) );
		
		//Get employee id of 'Alex'
		xpathExpression = "/employees/employee[firstName='Alex']/@id";
		System.out.println( evaluateXPath(document, xpathExpression) );
		
		//Get employee ids greater than 5
		xpathExpression = "/employees/employee/@id[. > 5]";
		System.out.println( evaluateXPath(document, xpathExpression) );
		
		//Get employee whose id contains 1
		xpathExpression = "/employees/employee[contains(@id,'1')]/firstName/text()";
		System.out.println( evaluateXPath(document, xpathExpression) );
		
		//Get employee whose id contains 1
		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;
	}
}

程序输出:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 8]
[3]
[6, 7, 8, 9, 10]
[Lokesh, Gary]
[Lokesh, Gary]

2.2.模型类

@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 + "]";
	}
}

将有关如何使用 xpath 查找具有属性值的 xml 元素的问题交给我。

快乐学习!!

标签2: Java XML XML Files XPath
地址:https://www.cundage.com/article/xpath-attribute-evaluate.html

相关阅读

Java xpath 示例 读取 XML 文件并解析为 DOM 对象,然后评估 org.w3c.dom.Document 对象上的 xpath 并获得结果以 String 或 NodeList ...
很多时候我们需要解析一个 XML 文件并从中提取信息。例如,使用 xpath 读取 XML 元素的属性值。在此 Java XPath 教程中,学习从 XML 字符串获取属性值。 我正在使用 jd...
如何使用 xpath 在 xml 中获取属性值的简单示例在爪哇。我们将学习获取信息以匹配属性值、范围内的属性值、xpath attribute contains() 等等。 1. XPath属性...
Java xpath 表达式示例,通过评估这些表达式从 XML 文档中提取信息。我们将学习获取信息以匹配属性值、匹配字段值、contains() 表达式等。 1. XPath 查询示例 1.1....
评估字符串的 xpath 并在字符串本身中返回结果 XML 的 Java 示例。 1. XPath 示例——在 xml 字符串上计算 xpath 创建包含 org.xml.sax.InputSo...
在此 java 示例中,我们将学习使用 NamespaceContext 具有命名空间声明和各自的用法。 命名空间添加了 XML 文件 我创建了 sample.xml 文件并放入类路径中。 &l...
使用 XPath 在给定 XML 内容中检查节点是否存在或在 XML 中检查属性是否存在的 Java 示例。 1、如何判断xml节点是否存在? 要验证节点或标记是否存在于 XML 内容中,您可以...
JDOM 解析器 可用于读取 XML、解析 xml 以及在更新 XML 文件内容后写入 XML 文件。它将JDOM2 文档 存储在内存中以读取和修改它的值。 将 XML 文档加载到内存后,JDO...
读取 XML 文件和打印 XML 字符串以控制或将 XML 写入文件的 Java 示例。 1) 将 XML 转换为字符串 转换 XML 对象即 org.w3c.dom.Document 成字符串...
在 Java 中,XML 用 org.w3c.dom.Document 对象表示。在本 XML 教程中,我们将学习 – 将 XML 字符串转换为 XML 文档 将 XML 文件内容转换为 XML...