使用dom4j操作xml文件的增删改
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用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文件的增删改的主要内容,如果未能解决你的问题,请参考以下文章