import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import net.sf.json.xml.XMLSerializer;
public class XmlBean {
public static Document GetDocument() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element author1 = root.addElement("Lynch");
author1.addAttribute("Age", "25");
author1.addAttribute("Country", "China");
author1.addText("I am great!");
Element author11 = author1.addElement("ssss");
author11.addAttribute("Age", "25");
author11.addAttribute("Country", "中国");
author11.addText("I am great!");
Element author2 = root.addElement("Legend");
author2.addAttribute("Age", "25");
author2.addAttribute("Country", "China");
author2.addText("I am great!too!");
return document;
}
public static String GetXMLString() {
StringWriter sw = new StringWriter();
XMLWriter writer = null;
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
try {
writer = new XMLWriter(format);
writer.setWriter(sw);
writer.write(GetDocument());
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(sw.toString());
return sw.toString();
}
public static void CreateXMLFile() {
try {
// Document document =
// DocumentHelper.parseText(GetXMLString());//将字符串转化为Document对象
Document document = GetDocument();// 自行构造Document对象
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileWriter(
"../json/src/demo3.xml"), format);// 格式化输出
// XMLWriter writer = new XMLWriter(new
// FileWriter("../json/src/demo3.xml"));
writer.write(document);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
可参阅:dom4j http://baike.baidu.com/view/1460716.htm