对xml文件的解析可以使用下述的依赖:
<!-- 解析xml文件 -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
项目目录结构如下:
NewFile.xml文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!--学生信息表-->
<Students>
<Student>
<Name class="name">张三</Name>
<Age>17</Age>
<Sex>男</Sex>
</Student>
<Student>
<Name class="name1">李四</Name>
<Age>20</Age>
<Sex>男</Sex>
</Student>
</Students>
解析代码:
public class XmlController {
public static void main(String[] args) throws DocumentException {
getXmlDocument();
}
public static void getXmlDocument() throws DocumentException {
String path=XmlController.class.getClassLoader().getResource("NewFile.xml").getFile();
System.out.println(path);
File file=new File(path);
SAXReader saxReader=new SAXReader();
Document document=saxReader.read(file);
Element root=document.getRootElement();
List<Element> elements=root.elements();
for (Element element : elements) {
for (Element node : element.elements()) {
System.out.println(node.getText());
}
}
}
}
输出结果:
张三
17
男
李四
20
男