用JDOM编写XML文件

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/*
 * 用JDOM写XML文档
 */
public class JDOM {
    
    public static void main(String[] args) throws FileNotFoundException, IOException {
        //构建一个文档
        Document document = new Document();
        //构建一个元素
        Element root = new Element("root");
        //把root加成根元素
        document.addContent(root);
        //构建一个注释
        Comment comment = new Comment("this is a comment");
        //把注释加到根元素上
        root.addContent(comment);
        //构建一个元素叫hello
        Element e = new Element("hello");
        //设置元素的属性sou为www.souhu.com
        e.setAttribute("sou","www.souhu.com");
        //把元素e加在root上
        root.addContent(e);
        //构建e2为world
        Element e2 = new Element("world");
        //设置属性为google的值为www.googel
        e2.setAttribute("google","www.google");
        //把e2加在了root上
        root.addContent(e2);
        //建立一个e3元素
        Element e3 = new Element("Hello");
        //构建一个属性名为text值为haha
        Attribute attr = new Attribute("text","haha");
        //把属性加在e3上
        e3.setAttribute(attr);
        //把e3加在root上
        root.addContent(e3);
        
        
        //设置文档的显示格式
        Format format = Format.getPrettyFormat();
        //缩进四个空格
        format.setIndent("    ");
        //设置输出流
        XMLOutputter out = new XMLOutputter(format);
        //把文档和文件用流关联起来
        out.output(document, new FileOutputStream("text.xml"));
        
    }

}

下面是生成的文件


<?xml version="1.0" encoding="UTF-8"?>
<root>
    <!--this is a comment-->
    <hello sou="www.souhu.com" />
    <world google="www.google" />
    <Hello text="haha" />
</root>



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值