JDOM创建XML文档实例

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

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class JDOMParserExample ... {

   
public static void main(String[] args)
       
throws IOException,FileNotFoundException,JDOMException...{
       
//实例化元素对象
        Element root=new Element("学校花名册");
        Element student
=new Element("学生");
        Element number
=new Element("学号");
        Element name
=new Element("姓名");
        Element age
=new Element("年龄");
       
//构造Document对象,设置文档根元素
        Document doc=new Document(root);
       
//设置学号的值
        number.setText("001");
       
//设置姓名的值
        name.setText("王五");
       
//设置年龄的值
        age.setText("26");
       
//添加学号子元素
        student.addContent(number);
       
//添加姓名子元素
        student.addContent(name);
       
//添加年龄子元素
        student.addContent(age);
       
//在根元素下添加学生子元素
        root.addContent(student);
       
//Format类用于设置文档的字符编码,设置行分隔符,以及设置缩进字符串等.
       
//getCompactFormat()方法,采用紧凑格式,这将会对文档中的空白进行规范化.
        Format format=Format.getCompactFormat();
       
//设置文档字符编码
        format.setEncoding("GB18030");
       
//设置缩进字符串
        format.setIndent("  ");
       
//XMLOutputter类提供了将JDOM树输出为字节流的能力
        XMLOutputter XMLOut=new XMLOutputter(format);
       
//输出到文件
        XMLOut.output(doc,new FileOutputStream("student2.xml"));
        System.out.println(
"执行成功");
    }

}

生成的XML文档:

<? xml version="1.0" encoding="GB18030" ?>
< 学校花名册 >
 
< 学生 >
   
< 学号 > 001 </ 学号 >
   
< 姓名 > 王五 </ 姓名 >
   
< 年龄 > 26 </ 年龄 >
 
</ 学生 >
</ 学校花名册 >
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值