dom4jを使って、JavaでXMLファイルを出力
サンプルコード:
import java.io.*;
import org.dom4j.*;
import org.dom4j.io.*;
/**
* DOM4Jを使ってXMLファイルを出力
*
*/
public class WriteBookDemo {
static String [][] data = {
{“1001″,"en1″,"en2″,"en3″,"60″,"2005″,"en"},
{“1002″,"Web","Spring","Bruce","54″,"2008″,"en" },
{“1003″,"ja1″,"ja2″,"ja3″,"70″,"1970″,"ja" },
{“1004″,"ja11″,"ja12″,"ja13″,"45″,"1965″,"ja" }
};
/**
* @param args
*/
public static void main(String[] args) {
writeBook(“mybook.xml");
}
/**
* @param filenameはxmlファイル名
*/
public static void writeBook(String filename){
//1.Documentの声明
Document doc = DocumentHelper.createDocument();
//2. ルート要素
Element rootElmt = doc.addElement(“booklist");
//3. サブ要素
for(String[] book : data){
Element bookElmt
= rootElmt.addElement(“book");
//book要素に属性を追加
bookElmt.addAttribute(“isbn", book[0]);
bookElmt.addAttribute(“catalog", book[1]);
//book要素に4個子要素を追加
Element nameElmt
= bookElmt.addElement(“name");
nameElmt.addAttribute(“lang", book[6]);
//name要素にデータを追加
nameElmt.setText(book[2]);
Element authorElmt
= bookElmt.addElement(“author");
authorElmt.setText(book[3]);
Element priceElmt
= bookElmt.addElement(“price");
priceElmt.setText(book[4]);
Element yearElmt
= bookElmt.addElement(“year");
yearElmt.setText(book[5]);
}
//4. 湧出
outputXml(doc, filename);
}
/**
* filenameにdocを書き込む
* @param doc ドキュメントオブジェクト
* @param filename xmlファイル名
*/
public static void outputXml(Document doc, String filename) {
try {
//出力ストリームを定義
FileWriter fw = new FileWriter(filename);
//フォーマットと文字セットを定義
OutputFormat format
= OutputFormat.createPrettyPrint();
format.setEncoding(“UTF8");
//xmlファイルのXMLWriterオブジェクトを定義
XMLWriter xmlWriter
= new XMLWriter(fw, format);
xmlWriter.write(doc);//*****
xmlWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}