java创建xml文件



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


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值