# Java XPath 从 XML 获取属性值 > 原文: [https://howtodoinjava.com/xml/xpath-get-attribute-value-xml/](https://howtodoinjava.com/xml/xpath-get-attribute-value-xml/) 很多时候,我们需要解析 XML 文件并从中提取信息。 例如,**使用 xpath** 读取 XML 元素的属性值。 在此 Java XPath 教程中,学习从 XML 字符串获取属性值。 我正在使用 [**jdom**](https://mvnrepository.com/artifact/org.jdom "jdom jar") 和 [**jaxen**](http://www.java2s.com/Code/Jar/j/Downloadjaxen111jar.htm "jaxen jar") 。 这些也是可用的其他大量开源 API,但是想法保持不变。 ## Java 程序使用 XPath 从 Java 中获得价值 在给定的 Java 程序下面,从提供的 XML 字符串创建 DOM 对象。 然后,它使用 **XPath.selectNodes()**方法应用 XPATH 表达式。 方法返回`Element`实例的列表,这些实例是评估 XPath 表达式的结果。 您可以迭代列表并使用结果。 ```java 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( " + " + Andre" + " + " + Peter" + " + " + Sandra" + " + "))); //Build the xpath expression XPath xpathExpression = XPath.newInstance("//*[@id]"); //Apply xpath and fetch all matching nodes ArrayList userIds = (ArrayList) 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()); } } } ``` 程序输出。 ```java 13423 32424 543534 ``` Please include correct class files. Invalid imports can cause in following error or something like this. ```java 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) ``` 学习愉快!