- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import org.jdom.Attribute;
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.output.Format;
- import org.jdom.output.XMLOutputter;
- public class generateXML {
- public static void main(String[] args) throws IOException {
- Document doc = new Document(); // 创建空白文档
- Element root = new Element("Root"); // 创建一个元素
- doc.setRootElement(root); // 将该元素做为根元素
- Element element = new Element("elementA");
- root.addContent(element); // 将product做为productsDetails的子元素
- Attribute att = new Attribute("attA", "中文"); // 创建属性
- element.setAttribute(att); // 为product设置属性
- // 为product创建子元素,并将其content分别设为100.00,red
- element.addContent(new Element("childA").setText("100"));
- element.addContent(new Element("childB").setText("200"));
- /*
- * 格式化输出
- */
- File file = new File("result.xml");
- XMLOutputter outp = new XMLOutputter();// 用于输出jdom 文档
- Format format = Format.getPrettyFormat(); // 格式化文档
- format.setEncoding("UTF-8"); // 设置编码格式为utf-8
- outp.setFormat(format);
- outp.output(doc, new FileOutputStream(file)); // 输出文档
- System.out.println("out put file done!");
- }
- }