Jdom写入

import java.io.FileWriter;
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包


//创建一Dom文档

Document document = new Document();
//创建一个根节点(必须有,并且只能有一个)
Element root = new Element("root");
//把根节点添加在dom文档中
document.addContent(root);
//注释
Comment comment = new Comment("This is my comments ");
//将注释添加在根节点中
root.addContent(comment);
//创建一个元素
Element e = new Element("班级");
//将元素属性和属性值(第一种方式添加属性方式)
e.setAttribute("id", "28");
//在根节点总加上一个元素
root.addContent(e);
//创建第二个元素
Element e2 = new Element("班号");
//创建一个属性和属性值
Attribute attr = new Attribute("名称", "2班");
//e2的元素添加属性(第二种方式添加属性方式)
e2.setAttribute(attr);
//将第二个元素添加到第一个元素中(第一种添加元素方式)
e.addContent(e2);
//还可以支持方法链的添加(第二种添加元素方式)
e2.addContent(new Element("aaa").setAttribute("a", "b").setAttribute(

"x", "y").setAttribute("gg", "hh").setText("小明"));//将在标签中添加文本


//获取格式或版式对象
Format format = Format.getPrettyFormat();
//将写入的xml有层次感
format.setIndent("    ");
//设置编码格式
format.setEncoding("UTF-8");
//创建XMLOutputter对象把dom文档写在硬盘上
XMLOutputter out = new XMLOutputter(format);
//调用output方法写入

out.output(document, new FileWriter("jdom.xml"));

写入如下

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <!--This is my comments -->
    <班级 id="28">
        <班号 名称="2班">
            <aaa a="b" x="y" gg="hh">小明</aaa>
        </班号>
    </班级>
</root>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值