使用dom4j来生成XML文件

package io.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

// 由java对像生成XML文件
public class XMLDemo
{
public static void main(String[] args)
    {
    Document document = DocumentHelper.createDocument();
   
    Element root = document.addElement("root");
   
    Element students = root.addElement("students");
   
    File file = new File("F:\\temp\\test.xml");
    if (file.exists())
    {
    file.delete();
    }
    Student[] stu = new Student[5];
    for (int i=0; i<5; i++)
    {
    stu[i] = new Student("name"+i, "id"+i, i*100);
    }
    try
        {
    for (int j=0; j<stu.length; j++)
    {
    Element stuElement = students.addElement("student");
    stuElement.addElement("name").addText(stu[j].getName());
    stuElement.addElement("id").addText(stu[j].getId());
    stuElement.addElement("height").addText(String.valueOf(stu[j].getHeight()));
    }
   
    FileOutputStream fileStream = new FileOutputStream(file);
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileStream, "UTF-8");
       
    OutputFormat format = new OutputFormat();
      
        format.setIndent(true);/// 缩排
        format.setIndent("    "); // 缩排长度
        format.setNewlines(true);// 折行
       
    XMLWriter writer = new XMLWriter(outputStreamWriter, format);
       
        writer.write(document);
        outputStreamWriter.close();
        fileStream.close();
       
        writer.close();
        System.out.println("success....");
        }
        catch (UnsupportedEncodingException e)
        {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        catch (FileNotFoundException e)
        {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        catch (IOException e)
        {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
    }

}
==================
生成的结果如下;
<?xml version="1.0" encoding="UTF-8"?>

<root>
    <students>
        <student>
            <name>name0</name>
            <id>id0</id>
            <height>0</height>
        </student>
        <student>
            <name>name1</name>
            <id>id1</id>
            <height>100</height>
        </student>
        <student>
            <name>name2</name>
            <id>id2</id>
            <height>200</height>
        </student>
        <student>
            <name>name3</name>
            <id>id3</id>
            <height>300</height>
        </student>
        <student>
            <name>name4</name>
            <id>id4</id>
            <height>400</height>
        </student>
    </students>
</root>

猜你喜欢

转载自pretyliang-163-com.iteye.com/blog/1670723