/**
* 產生xml檔案
* @throws IOException
* @throws JDOMException
*/
public void BuildXMLDoc() throws IOException, JDOMException {
// 建立根節點 list;
Element root = new Element("country");
root.setAttribute("code", "86");
root.setAttribute("name", "中國");
// 根節點添加到文檔中;
Document Doc = new Document(root);
QueryDAO dao = new QueryDAO();
List<Bean> provinces = dao.queryAllProvince();
// 此處 for 迴圈可替換成 遍曆 資料庫表的結果集操作;
for (Bean province:provinces) {
// 建立節點 user;
Element elProvince = new Element("province");
// 給 省 節點添加屬性 id;
elProvince.setAttribute("name", province.getName().trim());
elProvince.setAttribute("code", province.getId()+"");
// 給 user 節點添加子節點並賦值;
List<Bean> citys = dao.queryCityByProviceId(province.getId());
for(Bean city:citys){
Element elCity = new Element("city");
elCity.setAttribute("name",city.getName().trim());
elCity.setAttribute("code",city.getId()+"");
List<Bean> countrys = dao.queryCountryByCityId(city.getId());
for(Bean country:countrys){
Element clCountry = new Element("county");
clCountry.setAttribute("name",country.getName().trim());
clCountry.setAttribute("code",country.getId()+"");
elCity.addContent(clCountry);
}
elProvince.addContent(elCity);
}
// 給父節點list添加user子節點;
root.addContent(elProvince);
}
XMLOutputter XMLOut = new XMLOutputter();
Format f =Format.getPrettyFormat();
f.setEncoding("utf-8");
XMLOut.setFormat(f);
// 輸出 user.xml 檔案;
XMLOut.output(Doc, new FileOutputStream("F:/Area.xml"));
}
/**
* @param args
*/
public static void main(String[] args) {
CreateXML cx = new CreateXML();
try {
cx.BuildXMLDoc();
System.out.println("檔案產生成功!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}