既然可以從XML中取得所需要的資料,當然也應該可以把自己的資料寫入生成XML檔案。由于XML是可擴充标記語言,是以如果沒有特定DTD或者Schema約定的話,生成的XML檔案标簽及屬性的具體寫法你可以按個人習慣(當然一般情況下應該是有約定的,這樣你就隻有按照DTD或者Schema的規定來生成了)。
寫個簡單的例子,在把一個簡單的資訊輸出到E:/temp下的output.xml中。
XMLWriter.java
public class XMLWriter {
/**
* <selects>
* <select>
* <id>1</id>
* <name>北京市</name>
* </select>
* <id>2</id>
* <name>上海市</name>
* </selects>
*
*/
public static void main(String[] args) {
/*先生成目标Elements并建立各Element之間的關系*/
Element rootElt=new Element("selects");
Element selectElt=new Element("select");
Element idElt=new Element("id");
idElt.addContent("1");
Element valueElt=new Element("name");
valueElt.addContent("北京市");
selectElt.addContent(idElt);
selectElt.addContent(valueElt);
Element selectElt2=new Element("select");
Element idElt2=new Element("id");
idElt2.addContent("2");
Element valueElt2=new Element("name");
valueElt2.addContent("上海市");
selectElt2.addContent(idElt2);
selectElt2.addContent(valueElt2);
rootElt.addContent(selectElt);
rootElt.addContent(selectElt2);
/*
* 生成xml檔案
*/
//得到根節點
Document doc=new Document(rootElt);
//使用JDOM提供的XMLOutputter類輸出
XMLOutputter out=new XMLOutputter();
//設定xml檔案的Encoding
out.setFormat(Format.getCompactFormat().setEncoding("gb2312"));
//我這裡先列印檢視一下生成的字元串
String xmlStr=out.outputString(doc);
System.out.println(xmlStr);
try {
//進行資料輸出
out.output(doc, new FileOutputStream("E:/temp/output.xml"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
}
本文轉自NightWolves 51CTO部落格,原文連結:http://blog.51cto.com/yangfei520/301251,如需轉載請自行聯系原作者