使用JDOM创建xml文件

来源:互联网 发布:网络药品销售 编辑:程序博客网 时间:2024/05/17 03:49

代码比较清晰。

package comz.engine;//jdom包为jdom.jarimport java.io.FileOutputStream;import java.io.IOException;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.output.XMLOutputter;public class TestCreateXml {public void BuildXMLDoc() throws IOException, JDOMException {// 创建根节点 list;Element root = new Element("data");// 根节点添加到文档中;Document Doc = new Document(root);// 创建节点 users;Element elements11 = new Element("users");// 创建users节点下的user;Element elements12 = new Element("user");elements11.addContent(elements12);// 给 user 节点添加属性 id;// elements.setAttribute("id", "" + i);// 创建节点下的属性,同事也可以遍历创建elements12.addContent(new Element("a").setText("xuehui"));elements12.addContent(new Element("b").setText("28"));elements12.addContent(new Element("c").setText("Male"));elements12.addContent(new Element("d").setText("Male"));elements12.addContent(new Element("e").setText("Male"));// 给父节点list添加users子节点;root.addContent(elements11);// 创建节点 security;Element elements21 = new Element("s");elements21.addContent(new Element("m").setText("xuehui"));elements21.addContent(new Element("n").setText("28"));elements21.addContent(new Element("o").setText("Male"));// 给父节点list添加security子节点;root.addContent(elements21);XMLOutputter XMLOut = new XMLOutputter();// 输出 user.xml 文件;XMLOut.output(Doc, new FileOutputStream("E:/user.xml"));}public static void main(String[] args) {try {TestCreateXml x = new TestCreateXml();System.out.println("生成 mxl 文件...");x.BuildXMLDoc();} catch (Exception e) {e.printStackTrace();}}}