jdom单机测试生成xml文件

来源:互联网 发布:管家婆软件是什么 编辑:程序博客网 时间:2024/05/22 12:15
package test; import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import org.jdom.Document;import org.jdom.Element;import org.jdom.output.Format;import org.jdom.output.XMLOutputter;public class Export {    public static void main(String[] args) {        try {              Export j2x = new Export();              System.out.println("生成 mxl 文件成,测试.xml文件!");              j2x.Build();          } catch (Exception e) {              e.printStackTrace();          }         }    public void Build() throws FileNotFoundException, IOException{          //定义 名称         String name = "姓名";          String age = "年龄";          Format format = Format.getPrettyFormat();        //设置编码        format.setEncoding("GBK");        // 创建根节点 list;              Element root = new Element("list");         // 创建节点 user;              //添加xml的标签         Element elements = new Element("user");           // 给 user 节点添加属性 id;               elements.setAttribute("id", 1+"");           // 给 user 节点添加子节点并赋值;               // 赋值;               elements.addContent(new Element(name).setText("xiaoli"));           elements.addContent(new Element(age).setText("20"));           root.addContent(elements);       // 节点添加到文档中;              Document Doc = new Document(root);        XMLOutputter XMLOut = new XMLOutputter();        XMLOut.setFormat(format);        // 输出 XMLOutput.xml 文件到项目根目录;             XMLOut.output(Doc, new FileOutputStream("测试.xml"));      }}