1. 程式人生 > >使用dom4j操作xml文件的增刪改

使用dom4j操作xml文件的增刪改

使用dom4j操作xml文件的增刪改

package day2.domx; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.junit.Test; //使用dom4j操作xml文件的cud public class Dome2 { private final String path = "src/day2/domx/car.xml"; //xml路徑 @Test public void create() throws Exception{ Document document = getDocument(); Element rootElement = document.getRootElement(); //取得第一輛汽車 Element firstCarElement = (Element) rootElement.elements().get(0); //添加新元素"單價",並設置文本為30 firstCarElement.addElement("單價").setText("40"); //將內存中的xml文件寫到硬盤中 write2xml(document); } @Test public void update() throws Exception{ Document document = getDocument(); Element rootElement = document.getRootElement(); Element firstCarElement = (Element) rootElement.elements().get(0); firstCarElement.element("單價").setText("60"); write2xml(document); } @Test public void delete() throws Exception{ Document document = getDocument(); Element rootElement = document.getRootElement(); Element firstCarElement = (Element) rootElement.elements().get(0); Element firstCarPriceElement = firstCarElement.element("單價"); firstCarElement.remove(firstCarPriceElement); //firstCarPriceElement.getParent().remove(firstCarPriceElement); write2xml(document); } private void write2xml(Document document) throws Exception { OutputFormat format = OutputFormat.createPrettyPrint(); OutputStream os = new FileOutputStream(path); XMLWriter xmlWriter = new XMLWriter(os,format); //有中文使用formant格式 xmlWriter.write(document); xmlWriter.close(); } private Document getDocument() throws Exception { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(new File(path)); return document; } }

使用dom4j操作xml文件的增刪改