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 Dom4JXML
{
public void
createXML() {
//用工厂类创建一个document实例
Document doc =
DocumentHelper.createDocument();
//创建根元素emps
Element rootEle = doc.addElement("tests");
//添加注释
rootEle.addComment("这是一个dom4j生成的xml文件");
//emps根节点下创建一个emp节点
Element empEle = rootEle.addElement("test");
//emp添加属性id="1"
empEle.addAttribute("id", "1");
//emp节点下创建一个name节点
Element nameEle = empEle.addElement("name");
//name节点下创建一个文本节点zhangsan
nameEle.setText("zhangsan");
//再为name节点创建一个兄弟节点
Element sexEle = empEle.addElement("sex");
sexEle.setText("man");
//将document中的内容写入文件中
try
{
Writer out =
new FileWriter("D:\\tests.xml");
//格式化输出,类型IE浏览一样
OutputFormat format =
OutputFormat.createPrettyPrint();
//OutputFormat format =
OutputFormat.createCompactFormat();
format.setEncoding("UTF-8");
//创建写出对象
XMLWriter writer = new
XMLWriter(out,format);
writer.write(doc);
writer.close();
System.out.println("生成tests.xml成功。");
}
catch (IOException e) {
//
TODO Auto-generated catch block
e.printStackTrace();
System.out.println("失败了。");
}
}
public static void
main(String[] args) {
new Dom4JXML().createXML();
}
}
阅读(692) | 评论(0) | 转发(0) |