[转]java版自动生成xml代码
package com.xh.xml;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class Java2XML {
public void BuildXMLDoc() throws IOException, JDOMException {
Element root = new Element("root");
// 根节点添加到文档中;
Document Doc = new Document(root);
// 此处 for 循环可替换成 遍历 数据库表的结果集操作;
for (int i = 0; i < 10; i++) {
Element elements = new Element("vip");
elements.addContent(new Element("name").setText("xuehui"));
elements.addContent(new Element("age").setText("28"));
elements.addContent(new Element("sex").setText("Male"));
// 给父节点list添加user子节点;
root.addContent(elements);
}
// 输出 user.xml 文件;
Format format = Format.getPrettyFormat();
XMLOutputter XMLOut = new XMLOutputter(format);
XMLOut.output(Doc, new FileOutputStream("user.xml"));
}
public static void main(String[] args) {
try {
Java2XML j2x = new Java2XML();
System.out.println("生成 mxl 文件...");
j2x.BuildXMLDoc();
} catch (Exception e) {
e.printStackTrace();
}
}
}