package com.logic.demo;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
public class TestDemo {
public static void main(String[] args) throws Exception {
List<Student> students = new ArrayList<Student>();
// 1、创建DOM4J解析器
SAXReader reader = new SAXReader();
//2、解析具体的XML文件
Document document = reader.read("students.xml");
//3、获得XML中的根元素,一切解析从根元素开始
Element root = document.getRootElement();
//4、通过根元素获取某个子元素的集合
@SuppressWarnings("unchecked")
List<Element> list = root.elements("student");
for (Element element : list) {
String id = element.attributeValue("id");
Student student = new Student();
student.setId(id);
//element.elementText("name") 通过子元素名称,获取其对应文本值
String name = element.elementText("name");
String age = element.elementText("age");
student.setName(name);
student.setAge(Integer.parseInt(age));
students.add(student);
}
for (Student stu : students) {
System.out.println(stu);
}
}
@Test
public void testCreateXML() throws Exception{
//创建一个元素
Element root = DocumentHelper.createElement("students");
//指定这个元素为根,创建一个Document,返回一个Document
Document document = DocumentHelper.createDocument(root);
//在根下添加一个子元素,名为student
for(int i = 0; i < 3; i++){
Element student = root.addElement("student");
student.addAttribute("id", "1001");
student.addElement("name").addText("zhangsan1");
student.addElement("age").addText("8");
}
OutputStream os = new FileOutputStream("g:/students.xml");
OutputFormat format = new OutputFormat(" ",true);
//创建XML输入字符流
XMLWriter writer = new XMLWriter(os,format);
//写入dom
writer.write(document);
writer.close();
os.close();
}
}
DOM4Jj解析
最新推荐文章于 2024-10-31 21:56:54 发布