package com.fq.fanqi;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class TaoDaShen {
public void analysis(File file) throws IOException {
//创建一个文档模型
Document document = DocumentHelper.createDocument();
//定义一个根节点
Element root = document.addElement("parameters");
//根节点下添加子节点
Element paramer1 = root.addElement("tao");
//节点添加属性
paramer1.addAttribute("taodashen", "淘大婶");
//节点添加文本
paramer1.addText("大婶好");
Element paramer2 = root.addElement("zhou");
paramer2.addAttribute("xiaozhou", "mengwa");
paramer2.addText("萌娃娃");
Element paramer3 = root.addElement("xu");
paramer3.addAttribute("xinyi", "teacher");
Element guodaxia = paramer3.addElement("guowei");
guodaxia.addAttribute("name", "guo");
guodaxia.addAttribute("ming", "daxia");
guodaxia.addText("郭大侠");
//创建XML格式
StringWriter stringWriter = new StringWriter();
OutputFormat xmlFormat = new OutputFormat();
xmlFormat.setEncoding("UTF-8");
xmlFormat.setNewlines(true);
xmlFormat.setIndent(" ");
FileWriter fileWriter = new FileWriter(file);
XMLWriter xmlWriter = new XMLWriter(fileWriter,xmlFormat);
xmlWriter.write(document);
xmlWriter.close();
}
public static void main(String[] args) throws IOException {
TaoDaShen taoDaShen = new TaoDaShen();
taoDaShen.analysis(new File("W:\\test.xml"));
}
}