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文件的cudpublic 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; }}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦