使用JDOM方式生成XML文件的步驟如下:
- 創建根節點
- 創建Document對象,並將根節點傳入其構造方法中
- 創建子節點,使用
setAttribute()
方法爲其設置屬性,使用setText()
方法爲其設置節點內容 - 使用父節點的
setContent()
方法爲其設置子節點 - 創建XMLOutputter對象
- 使用XMLOutputter對象的
output()
方法將Document轉換成XML文件
下面給出代碼:
package util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom2.CDATA;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.EscapeStrategy;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class XMLUtils {
public void createXMLByJDOM(File dest) {
// 創建根節點
Element rss = new Element("rss");
// 爲根節點設置屬性
rss.setAttribute("version", "2.0");
// 創建Document對象,併爲其設置根節點
Document document = new Document(rss);
Element channel = new Element("channel");
Element title = new Element("title");
// 設置節點內容,使用此方法會自動對特殊符號進行轉義
// title.setText("<![CDATA[上海移動互聯網產業促進中心正式揭牌 ]]>");
// 設置CDATA類型的節點內容,使用此方法會自動在內容兩邊加上CDATA的格式
CDATA cdata = new CDATA("上海移動互聯網產業促進中心正式揭牌");
title.setContent(cdata);
channel.setContent(title);
rss.setContent(channel);
// 創建XMLOutputter對象
XMLOutputter outputter = new XMLOutputter();
try {
// 方法一:創建Format對象(自動縮進、換行)
Format format = Format.getPrettyFormat();
// 爲XMLOutputter設置Format對象
outputter.setFormat(format);
// 方法二:創建Format對象,並設置其換行
// Format format = Format.getCompactFormat();
// format.setIndent("");
// 將Document轉換成XML
outputter.output(document, new FileOutputStream(dest));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
在使用JDOM生成XML時,可自行指定其輸出格式,有兩種方法可選。
方法一:
//方法一:創建Format對象(自動縮進、換行)
Format format = Format.getPrettyFormat();
//爲XMLOutputter設置Format對象
outputter.setFormat(format);
方法二:
//方法二:創建Format對象,並設置其換行
Format format = Format.getCompactFormat();
format.setIndent("");
JDOM也會自動將特殊符號進行轉義。若內容爲CDATA數據,可創建一個CDATA對象,再將該對象設爲子節點即可。這樣,特殊符號不會進行自動轉義。
//設置CDATA類型的節點內容,使用此方法會自動在內容兩邊加上CDATA的格式
CDATA cdata = new CDATA("上海移動互聯網產業促進中心正式揭牌");
title.setContent(cdata);