当前位置: 首页 > 工具软件 > JDOM > 使用案例 >

Jdom写入

郜彦
2023-12-01

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>

 类似资料: