以下是源代码:
package com.yangshu.xml.dom4j;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
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 Dome3 {
@Test
public void crate() throws Exception{
Document document = getDocument();
//找根元素
Element rootElement = document.getRootElement();
//获得根元素下第一个元素。
Element firstCarElement = (Element) rootElement.elements().get(0);
//添加一个元素“单价”内容为:40
firstCarElement.addElement("单价").setText("40");
//写xml
writer2Xml(document);
}
//对xml文件操作--写
private void writer2Xml(Document document)
throws FileNotFoundException, UnsupportedEncodingException,
IOException {
//缩进格式输出
OutputFormat of = OutputFormat.createPrettyPrint();
//输出流
OutputStream os = new FileOutputStream("src/com/yangshu/xml/dom4j/car.xml");
//对XML文件写的操作作对象
XMLWriter xmlWriter = new XMLWriter(os,of);
//网xml文件写
xmlWriter.write(document);
//关闭流
xmlWriter.close();
}
//这个方法就是获取xml文档对象
private Document getDocument() throws DocumentException {
//SAXReader解析器
SAXReader saxReader = new SAXReader();
//加载xml文件
Document document =saxReader.read(new File("src/com/yangshu/xml/dom4j/car.xml"));
return document;
}
}
让编程变的更好理解