package com.haven.reply.serviceimpl; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.jdom.Comment; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; public class JavaXMLDaoImpl { public void createXMLDoc() { // 创建根节点 root; Element root = new Element("root"); // 根节点添加到文档中; 根节点是唯一的 Document Doc = new Document(root); // 下面开始向XML文档中插入数据 // 创建节点elemets1; Element elements1 = new Element("elemets1"); // 给 elemets 节点添加属性 name; elements1.setAttribute("name", "test1"); // 给 elemets 节点添加子节点并赋值; elements1.addContent(new Element("note1-1").setText("value1-1")); elements1.addContent(new Element("note1-2").setText("value1-2")); // 添加一个注释 elements1.addContent(new Comment("This is Comment!!!!")); elements1.addContent(new Element("note1-3").setText("value1-3")); // 给父节点list添加user子节点; root.addContent(elements1); // 继续创建节点elemets2;方法和步骤和elemets1完全一样 Element elements2 = new Element("elemets2"); // 给 elemets 节点添加属性 name; elements2.setAttribute("name", "test2"); // 给 elemets 节点添加子节点并赋值; elements2.addContent(new Element("note2-1").setText("value2-1")); elements2.addContent(new Element("note2-2").setText("value2-2")); elements2.addContent(new Comment("This is Comment!!!!")); elements2.addContent(new Element("note2-3").setText("value2-3")); root.addContent(elements2); // 下面是美化工作,如果不进行排版,生成的XML全部在一行显示。可读性很差 Format format = Format.getCompactFormat(); format.setEncoding("UTF-8"); format.setIndent(" "); // 缩进4个空格后换行 XMLOutputter XMLOut = new XMLOutputter(format); // test.xml为生成的xml文档名 try { XMLOut.output(Doc, new FileOutputStream("test.xml")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { try { JavaXMLDaoImpl j2x = new JavaXMLDaoImpl(); System.out.println("生成 mxl 文件..."); j2x.createXMLDoc(); } catch (Exception e) { e.printStackTrace(); } } } |
|