package study;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class Demo_01 {
public static void main(String[] args) throws Exception {
//通过DocumentHelper生成一个document对象
Document doc = DocumentHelper.createDocument();
//添加并得到根元素
Element root = doc.addElement("books");
//为根元素添加子元素
Element book = root.addElement("book");
//添加属性
book.addAttribute("id", "01");
//为book添加子元素
Element name = book.addElement("name");
Element author = book.addElement("author");
Element price = book.addElement("price");
//为子元素添加文本
name.addText("C++编程");
author.addText("王五");
price.addText("66.66");
//将上面所有的东西输入到XML文件中
Writer w = new FileWriter("src/books.xml");
OutputFormat of = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(w, of);
writer.write(doc);
//关闭
w.close();
}
}
6.创建格式良好的XML文件
最新推荐文章于 2022-07-09 10:30:00 发布