Java XPath 从 XML 获取属性值

Java XPath 从 XML 获取属性值

原文: https://howtodoinjava.com/xml/xpath-get-attribute-value-xml/

很多时候,我们需要解析 XML 文件并从中提取信息。 例如,使用 xpath 读取 XML 元素的属性值。 在此 Java XPath 教程中,学习从 XML 字符串获取属性值。

我正在使用 jdomjaxen。 这些也是可用的其他大量开源 API,但是想法保持不变。

使用 XPath 从 Java 中获得值的 Java 程序

在给定的 Java 程序下面,从提供的 XML 字符串创建 DOM 对象。 然后,它使用XPath.selectNodes()方法应用 XPATH 表达式。

方法返回Element实例的列表,这些实例是求值 XPath 表达式的结果。 您可以迭代列表并使用结果。

package com.howtodoinjava.xml;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class XmlAttributesUsingXPathExample
{
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws JDOMException, IOException
	{
		Document doc = new SAXBuilder(false).build(new StringReader(new String(
                                               <users>	" +
													<user id='13423'>" +
														<firstname>Andre</firstname>" +
													</user>" +
													<user id='32424'>" +
														<firstname>Peter</firstname>" +
													</user> " +
													<user id='543534'>" +
														<firstname>Sandra</firstname>" +
													</user>" +
												</users>")));

		//Build the xpath expression
		XPath xpathExpression = XPath.newInstance("//*[@id]");

		//Apply xpath and fetch all matching nodes
		ArrayList<Element> userIds =  (ArrayList<Element>) xpathExpression.selectNodes(doc);

		//Iterate over naodes and print the value
		for (int i = 0; i < userIds.size(); i++)
        {
        	System.out.println((userIds.get(i)).getAttributeValue("id").trim());
        }
	}
}

程序输出。

13423
32424
543534

请包括正确的类文件。 无效的导入会导致以下错误或类似的错误。

java.lang.ClassCastException: org.jdom.Document cannot be cast to org.w3c.dom.Node
at com.sun.org.apache.xpath.internal.jaxp.XPathExpressionImpl.eval(XPathExpressionImpl.java:116)
at com.sun.org.apache.xpath.internal.jaxp.XPathExpressionImpl.eval(XPathExpressionImpl.java:98)
at com.sun.org.apache.xpath.internal.jaxp.XPathExpressionImpl.evaluate(XPathExpressionImpl.java:180)

学习愉快!