/**
* 生成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();
}
}