读取xml文件一般会使用dom4j
官网:dom4j
这里来介绍一下简单使用
创建一个maven项目
导入依赖:
<dependencies>
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
</dependencies>创建一个xml文件待读取
<?xml version="1.0" encoding="utf-8" ?>
<root>
<user id="001">
<name>Dreams</name>
<password>123456</password>
</user>
</root>读取方式如下:
package org.example;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.net.URL;
import java.util.List;
/**
* @author PoemsAndDreams
* @date 2024-02-17 18:50
* @description //TODO $end
*/
public class Main {
public static void main(String[] args) {
Main main = new Main();
//创建一个解析器
SAXReader saxReader = new SAXReader();
try {
String fileName = "test.xml";
URL resource = main.getClass().getClassLoader().getResource(fileName);
//读取xml文件
Document document = saxReader.read(resource);
//获取根节点
Element root = document.getRootElement();
System.out.println("根节点名字 :" + root.getName());
//获取根节点下的子节点
List<Element> rootElements = root.elements();
for (Element rootElement : rootElements) {
List<Element> elements = rootElement.elements();
System.out.println("子节点名字 :" + rootElement.getName());
Attribute attributeValue = rootElement.attribute("id");
String value = attributeValue.getValue();
System.out.println("子节点的id值 :" + value);
System.out.println("-----------");
for (Element element : elements) {
System.out.println(element.getName() + "的值 :" + element.getText());
}
}
} catch (DocumentException e) {
throw new RuntimeException(e);
}
}
}加上注释的代码通俗易懂,不在阐述
输出结果如下:



