1.准备工具:
dom4j依赖:
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
junit测试工具依赖:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
自定义xml文件student.xml:
<?xml version="1.0" encoding="utf-8"?>
<students>
<student banji="1班">
<name>小红书</name>
<number>1411124</number>
<age>12</age>
</student>
<student banji="2班">
<name>小明</name>
<number>1411125</number>
<age>16</age>
</student>
</books>
2.解析xml
public class Dom4jTest {
@Test
public void test1(){
//获取SAXReader输入流
SAXReader saxReader = new SAXReader();
try {
/**
*1.读取book.xml文件并返回Document对象,
*/
Document document = saxReader.read("student.xml");
//2.读取文件的根元素
Element root = document.getRootElement();
List<Element> students = root.elements();
// asXML() 把标签对象,转化为标签字符串
for(Element student : students){
System.out.println(student.asXML());
Element nameElement = student.element("name");
System.out.println(nameElement.asXML());
System.out.println(nameElement.getText());
//getText(); 可以获取标签中的文本内容
//elementText() 可以获取标签中的内容
//直接获取属性中的值
String sn = student.attributeValue("banji");
String name = student.elementText("name");
int age = Integer.parseInt(student.elementText("age"));
String number = student.elementText("number");
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}