要求:
1.生成一个XML文档:
<?xml version="1.0" encoding="utf-8"?>
<Students>
<Student id="1">
<name>张三</name>
<gender>男</gender>
<grade>计算机一班</grade>
<address>广州天河</address>
</Student>
<Student id="2">
<name>李四</name>
<gender>女</gender>
<grade>计算机二班</grade>
<address>广州越秀</address>
</Student>
</Students>
2.将id为2的学生的姓名修改为张丽
实现代码:
package gz.itcast.a_dom4j_read;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
public class Demo_Write1 {
public static void main(String[] args) throws Exception {
//一、创建一个XML文档
Document doc = DocumentHelper.createDocument();//1.创建一个文档
Element rootElem = doc.addElement("Students");//2.创建标签
Element studentElem1 = rootElem.addElement("Student");//创建子标签
studentElem1.addAttribute("id", "1"); //3.添加属性
studentElem1.addElement("name").setText("张三");
studentElem1.addElement("gender").setText("男");
studentElem1.addElement("grade").setText("计算机一班");
studentElem1.addElement("address").setText("广州天河");
Element studentElem2 = rootElem.addElement("Student");//创建子标签
studentElem2.addAttribute("id", "2"); //3.添加属性
studentElem2.addElement("name").setText("李四");
studentElem2.addElement("gender").setText("女");
studentElem2.addElement("grade").setText("计算机二班");
studentElem2.addElement("address").setText("广州越秀");
//二、修改XML文档:修改id为2的姓名为张丽,代码见test1
//三、输出XML文件
FileOutputStream out = new FileOutputStream("f:/Student.xml");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(out,format);
writer.write(doc);
writer.close();
}
//二、修改XML文档:修改id为2的姓名为张丽,代码见test1
@Test
public void test1() throws Exception {
Document doc1 = new SAXReader().read(new File("f:/Student.xml"));
Iterator<Element> it = doc1.getRootElement().elementIterator("Student");
while(it.hasNext()){
Element stuElem = it.next();
System.out.println(stuElem.getName());
if(stuElem.attributeValue("id").equals("2")) {
stuElem.element("name").setText("张丽");
break;
}
}
FileOutputStream out = new FileOutputStream("f:/Student.xml");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(out,format);
writer.write(doc1);
writer.close();
}
}
标签:XML,dom4j,setText,writer,例子,文档,org,import,addElement From: https://blog.51cto.com/u_16079508/6207012