java获取xml节点的值
时间: 2023-02-07 18:54:45 浏览: 171
Java中可以使用XPath来获取XML文档中节点的值。
首先,需要创建一个`javax.xml.xpath.XPath`对象,然后使用`XPathExpression`来编译XPath表达式,最后使用`XPathExpression.evaluate`方法来执行XPath表达式并获取节点的值。
例如,下面的代码演示了如何使用XPath获取XML文档中的节点值:
```java
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
// ...
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
// 编译XPath表达式
XPathExpression expr = xpath.compile("/root/node/text()");
// 执行XPath表达式并获取节点列表
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
// 遍历节点列表并输出节点的值
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
```
其中,`doc`是一个`org.w3c.dom.Document`对象,表示XML文档。
注意,需要导入以下依赖才能使用上述代码:
```
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)