64.md 2.8 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10
# 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 中获得价值

W
wizardforcel 已提交
11
在给定的 Java 程序下面,从提供的 XML 字符串创建 DOM 对象。 然后,它使用 **XPath.selectNodes()**方法应用 XPATH 表达式。
W
wizardforcel 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

方法返回`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(
                                               <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());
        }
	}
}

```

程序输出。

```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)
```

学习愉快!