package com.itheima.xmlPare;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class XmlParse {
public static void main(String[] args) throws DocumentException {
// 1.获取文档对像
SAXReader saxReader=new SAXReader();
// 2.利用解析把xml文档加载到内存,并返回一个文档对象
Document document = saxReader.read(new File(".\\xml\\student.xml"));
// 3获取根标签
Element rootElement = document.getRootElement();
// 通过根标签获取student标签
// List list = rootElement.elements();
List<Element> listElment = rootElement.elements("student");
System.out.println(listElment.size());
ArrayList<Student> list=new ArrayList<>();
for (Element element : listElment) {
Attribute attribute = element.attribute("id");
String id = attribute.getValue();
Element nameElement = element.element("name");
String name = nameElement.getText();
Element ageElement = element.element("age");
String age = ageElement.getText();
// System.out.println(id);
// System.out.println(name);
// System.out.println(age);
Student s=new Student(id,name,Integer.parseInt(age));
list.add(s);
}
for (Student student : list) {
System.out.println(student);
}
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!--注释内容-->
<students>
<!-- 第一个个学生的信息-->
<student id="1">
<name>张三</name>
<age>23</age>
<info>学生<>信息</info>
<message><![CDATA[内容<<<<<]]]></message>
</student>
<!--第二个学生信息-->
<student id="2">
<name>李四</name>
<age>24</age>
</student>
<aaa></aaa>
</students>
|