java获取xml中多层节点的值_Java-XML技术
时间: 2023-10-03 19:03:56 浏览: 62
要获取 XML 中多层节点的值,可以使用 Java 中的 DOM 解析器。
以下是获取 XML 中多层节点值的示例代码:
```java
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLParser {
public static void main(String[] args) {
try {
File inputFile = new File("input.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("book");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
NodeList childList = nNode.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
Node childNode = childList.item(i);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
if (childNode.getNodeName().equals("title")) {
System.out.println("Title: " + childNode.getTextContent());
}
if (childNode.getNodeName().equals("author")) {
System.out.println("Author: " + childNode.getTextContent());
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上示例代码将会解析名为 "input.xml" 的 XML 文件,并获取节点名为 "book" 的节点下的 "title" 和 "author" 节点的值。其中,`NodeList` 类可以用来获取一组节点,`Node` 类可以用来表示一个节点,`getChildNodes()` 方法可以获取一个节点的所有子节点,`getTextContent()` 方法可以获取节点的文本内容。
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)