通过 JDOM 方式生成 XML 文档

1.引入jdom jar包

2.代码

     Element ele = new Element("tree");
        ele.setAttribute("id","0");
        
        Document document = new Document(ele);
        
        Element e1 = new Element("name");
        e1.setText("名称");
        ele.addContent(e1);
    
//        Format format = Format.getCompactFormat();//xml格式
        Format format = Format.getPrettyFormat();//xml格式
//        format.setIndent("");//设置换行,getPrettyFormat不用设
        format.setEncoding("GBK");
        
        XMLOutputter outputter = new XMLOutputter(format);
        try {
            outputter.output(document, new FileOutputStream(new File("jdomTest.xml")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

 

3.结果

<?xml version="1.0" encoding="GBK"?>
<tree id="0">
  <name>名称</name>
</tree>

 

posted @ 2015-01-15 14:31  知之为知之  阅读(127)  评论(0编辑  收藏  举报