项目结构
写在了src下的xml文件夹下
依赖包
dom4j 意思是 dom for java
我这里由于是测试,没有使用maven来管理依赖,因此我下载后存入了文件夹并add as library添加到了项目的依赖库中
xml内容
<?xml version="1.0" encoding="utf-8" ?>
<persons>
<person id="1">
<name>张三</name>
<age>18</age>
</person>
<person id="2">
<name>李四</name>
<age>20</age>
</person>
</persons>
读取代码
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.*;
import java.util.List;
/**
* 使用dom4j解析xml
*/
public class ParseXMLDemo {
public static void main(String[] args) throws IOException, DocumentException {
SAXReader reader = new SAXReader();
//打印下文件内容确保文件在
InputStream inputStream = ClassLoader.getSystemResourceAsStream("xml\\student.xml");
System.out.println("文件内容读取测试");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
//关闭流
inputStream.close();
bufferedReader.close();
System.out.println("\n\n");
System.out.println("xml读取测试");
InputStream is = ClassLoader.getSystemResourceAsStream("xml\\student.xml");
//读取整个文档
Document document = reader.read(is);
//拿根元素
Element rootElement = document.getRootElement();
List<Element> elements = rootElement.elements();
for (Element element : elements){
String tagName = element.getName();
String id = element.attribute("id").getValue();
System.out.println("标签名字:"+tagName+" id= "+ id);
if (tagName.equals("person")){
//继续读取名字和年龄
List<Element> list = element.elements();
for (Element element1 : list){
System.out.println(element1.getName()+":"+element1.getText());
}
}
}
//最后关闭流
is.close();
}
}