使用dom4j来生成XML文件

packageio.xml;

importjava.io.File;

importjava.io.FileNotFoundException;

importjava.io.FileOutputStream;

importjava.io.IOException;

importjava.io.OutputStreamWriter;

importjava.io.UnsupportedEncodingException;

importorg.dom4j.Document;

importorg.dom4j.DocumentHelper;

importorg.dom4j.Element;

importorg.dom4j.io.OutputFormat;

importorg.dom4j.io.XMLWriter;

//由java对像生成XML文件

publicclassXMLDemo

{

publicstaticvoidmain(String[]args)

{

Documentdocument=DocumentHelper.createDocument();

Elementroot=document.addElement("root");

Elementstudents=root.addElement("students");

Filefile=newFile("F:\\temp\\test.xml");

if(file.exists())

{

file.delete();

}

Student[]stu=newStudent[5];

for(inti=0;i<5;i++)

{

stu[i]=newStudent("name"+i,"id"+i,i*100);

}

try

{

for(intj=0;j<stu.length;j++)

{

ElementstuElement=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()));

}

FileOutputStreamfileStream=newFileOutputStream(file);

OutputStreamWriteroutputStreamWriter=newOutputStreamWriter(fileStream,"UTF-8");

OutputFormatformat=newOutputFormat();

format.setIndent(true);///缩排

format.setIndent("");//缩排长度

format.setNewlines(true);//折行

XMLWriterwriter=newXMLWriter(outputStreamWriter,format);

writer.write(document);

outputStreamWriter.close();

fileStream.close();

writer.close();

System.out.println("success....");

}

catch(UnsupportedEncodingExceptione)

{

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

catch(FileNotFoundExceptione)

{

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

catch(IOExceptione)

{

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

}

}

==================

生成的结果如下;

<?xmlversion="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>

相关推荐