java生成xml
java生成xml文件例子(dom4j)
急着要用,先生成一个很low的Demo,想了想,还是留下点笔记吧。
代码:
package com.ywx.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class XmlImpl {
public static void main(String[] args) {
try {
XmlTest.createXml("");//保留参数,此处我是生成一个例子,打算在用时传入对象。
} catch (Exception e) {
e.printStackTrace();
}
}
}
class XmlTest{
private static Document doc = DocumentHelper.createDocument();
public static void createXml(String fileName) throws Exception{
Element share = doc.addElement("share");
Element apply = share.addElement("apply");
Element code = share.addElement("code");
Element id = apply.addElement("id");
Element name = apply.addElement("name");
Element type = apply.addElement("type");
Element num = apply.addElement("num");
id.setText("123");
name.setText("vashon");
type.setText("行政");
num.setText("56");
Element ide = code.addElement("ide");
Element name1 = code.addElement("name1");
Element type1 = code.addElement("type1");
Element num1 = code.addElement("num1");
ide.setText("231");
name1.setText("王五");
type1.setText("材料Test");
num1.setText("76");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
XMLWriter writer = new XMLWriter(new FileOutputStream(new File("d:" + File.separator + "output.xml")),format);//输出路径
writer.write(doc);
writer.close();
}
}</span>
运行结果截图: