生成的类代码:
package com.xh.xml;
import 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 Java2XML {
public void BuildXMLDoc() throws IOException, JDOMException {
//创建根节点list;
Element root = new Element("list");
//根节点添加到文档中;
Document Doc = new Document(root);
//此处for循环可替换成 遍历 数据库表的结果集操作;
for (int i = 0; i < 2; i++) {
//创建节点user;
Element elements = new Element("user");
//给user节点添加属性id;
elements.setAttribute("id", "" + i);
//给user节点添加子节点并赋值;
// new Element("name")中的"name"替换成表中相应字段,setText("xuehui")中"xuehui替换成表中记录值;
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);
}
XMLOutputter XMLOut = new XMLOutputter();
//输出user.xml文件;
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();
}
}
}
生成的user.xml文件
xuehui
28
Male
xuehui
28
Male
生成XML时候处理缩进,对输出格式进行美化
只需要将上面生成XML时候的带吗修改成如下代码:
Format format = Format.getPrettyFormat();
XMLOutputter XMLOut = new XMLOutputter(format);
XMLOut.output(Doc, new FileOutputStream("user.xml"));
生成XML的时候,处理特殊字符
element.addContent(new CDATA(" content"));
生成XML的时候,设置编码
XMLOutputter XMLOut = new XMLOutputter();
XMLOut.setEncoding("gb2312");
XMLOut.output(Doc, new FileOutputStream("test1.xml"));