dom4j解析xml文档(增删改查)

时间:2021-10-06 04:56:20
 package itcast.dom4j;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List; import org.dom4j.Document;
import org.dom4j.DocumentException;
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 { // 在第一本书上添加一个新的售价:<price>209yuan</price>
@Test
public void add() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml")); Element book = document.getRootElement().element("书");
book.addElement("price").setText("209yuan"); OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),
format);
writer.write(document);
writer.close();
} @Test
public void add2() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml")); Element book = document.getRootElement().element("书");
List list = book.elements();// bookname/author/price Element price = DocumentHelper.createElement("price");
price.setText("309yuan"); list.add(2, price); OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),
format);
writer.write(document);
writer.close();
} @Test
public void delete() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml")); Element price = document.getRootElement().element("书").element("price");
price.getParent().remove(price); OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),
format);
writer.write(document);
writer.close();
} @Test
public void update() throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/book.xml")); Element book = (Element) document.getRootElement().elements("书").get(1);
book.element("editor").setText("zero"); OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8"); XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),
format);
writer.write(document);
writer.close();
} }
 <?xml version="1.0" encoding="UTF-8"?>

 <书架>
<书>
<bookname name="zero">java jiuyepeixunjiaocheng</bookname>
<editor>zhangxiaoxiang</editor>
<price>209yuan</price>
</书>
<书>
<bookname name="one">javaWebprogramming</bookname>
<editor>zero</editor>
<price>28.00yuan</price>
</书>
</书架>