利用DOM4J对XML进行简单的CRUD

package cn.itcast.xml.parser.dom4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import org.dom4j.Document;
import org.dom4j.DocumentException;
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 Demo2 {
	private Document getDocument() throws Exception{
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File("src/cn/itcast/xml/parser/dom4j/car.xml"));
		return document;
	}
	private void writerToFile(Document document)throws Exception{
		//取得输出格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		//设置XML输出的编码方式
		format.setEncoding("UTF-8");
		//将内存中的字节转换成字符
		Writer writer = new OutputStreamWriter(new FileOutputStream("src/cn/itcast/xml/parser/dom4j/car.xml"),"UTF-8");
		//创建dom4j的输出字符流
		XMLWriter xmlWriter = new XMLWriter(writer,format);
		//真正输出
		xmlWriter.write(document);
		//关闭流
		xmlWriter.close();
	}
	@Test
	public void create() throws Exception{
		Document document = this.getDocument();
		Element rootElement = document.getRootElement();
		Element carElement = rootElement.element("汽车");
		carElement.addElement("单价").setText("25万");
		this.writerToFile(document);
	}
	@Test
	public void update() throws Exception{
		Document document = this.getDocument();
		Element rootElement = document.getRootElement();
		Element carElement = (Element) rootElement.elements("汽车").get(1);
		carElement.element("产地").setText("广州");
		this.writerToFile(document);
	}
	@Test
	public void delete() throws Exception{
		Document document = this.getDocument();
		Element rootElement = document.getRootElement();
		Element priceElement = rootElement.element("汽车").element("单价");
		priceElement.getParent().remove(priceElement);
		this.writerToFile(document);
	}
}













 

你可能感兴趣的:(java,xml,JUnit)