DOM4J解析XML檔案
public class DOM4JTest1 {
public static void main(String[] args) throws DocumentException {
//1.建立解析的類
SAXReader reader = new SAXReader();
//2.開始解析 形成文檔樹
Document document = reader.read("D:/mycode/XML/teacher/students2.xml");
//3.擷取根節點
Element rootElement = document.getRootElement();
//4.擷取位元組點
List<Element> students = rootElement.elements("student");
for (Element student : students) {
//5.擷取屬性
//擷取指定的屬性
Attribute attribute = student.attribute("id");
System.out.println(attribute.getName()+"<===>"+attribute.getValue());
/*
擷取所有的屬性
List<Attribute> attributes = student.attributes();
for (Attribute attribute : attributes) {
System.out.println(attribute.getName()+"<===>"+attribute.getValue());
}*/
//6.擷取孫子元素
List<Element> childStudents = student.elements();
//7.擷取孫子元素的内容
childStudents.forEach((x)->{
System.out.println( x.getName()+"<======>"+x.getText());
});
/* for (Element x : childStudents) {
System.out.println( x.getName()+"<======>"+x.getText());
}*/
System.out.println();
}