Jdom写XML

来源:互联网 发布:wind万德数据库 编辑:程序博客网 时间:2024/05/01 06:02
package com.zuxia.jdom;

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

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

/**
 *
 * 写xml文件
 *
 * @author Administrator
 *
 */
public class WriterXML {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        
        //1. 创建根节点
        Element root = new Element("class");
        
        Element stu = new Element("student");
        
        Element name = new Element("name");
        name.setText("李斯");
        
        Element sex = new Element("sex");
        sex.setText("女");
        
        Element age = new Element("age");
        age.setText("20");
        
        Element score = new Element("score");
        score.setAttribute("java", "90").setAttribute("oracle", "100");
        
        //添加节点之间的关系
        root.addContent(stu);        
        stu.addContent(name).addContent(sex).addContent(age).addContent(score);
        
        //写入文件中(只能成document)
        //将节点转换成文档
        Document doc = new Document(root);
        
        //格式设置
        Format fmt = Format.getCompactFormat();
        fmt.setIndent("    ");
        
        //写入
        XMLOutputter out = new XMLOutputter(fmt);
        
        out.output(doc, new FileOutputStream("e:/studentinfo.xml"));
        
        System.out.println("success!!!");
        
    } 
}

原创粉丝点击