/**
* Desciption: Java create XML file
* Author: Maomao
* Datetime: 2007/04/04 23:42
*/
Package com. XH. xml;
Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Import org. JDOM. Document;
Import org. JDOM. element;
Import org. JDOM. jdomexception;
Import org. JDOM. Output. xmloutputter;
Publicclass java2xml {
Publicvoid buildxmldoc () throws ioexception, jdomexception {
// Create a list of root nodes;
Element root = new element ("list ");
// Add the root node to the document;
Document Doc = new document (Root );
// Here, The for loop can be replaced with the result set operation for Traversing database tables;
For (INT I = 0; I <5; I ++ ){
// Create a node user;
Element elements = new element ("user ");
// Add the property ID to the user node;
Elements. setattribute ("ID", "" + I );
// Add a subnode to the user node and assign a value to it;
// Replace "name" in new element ("name") with the corresponding field in the table, and "Xuehui" in settext ("Xuehui") with the record value in the table;
Elements. addcontent (new element ("name"). settext ("Xuehui "));
Elements. addcontent (new element ("Age"). settext ("28 "));
Elements. addcontent (new element ("sex"). settext ("male "));
// Add a user subnode to the parent node list;
Root. addcontent (elements );
}
Xmloutputter xmlout = new xmloutputter ();
// Output the user. xml file;
Xmlout. Output (Doc, new fileoutputstream ("user. xml "));
}
Publicstaticvoid main (string [] ARGs ){
Try {
Java2xml j2x = new java2xml ();
System. Out. println ("generate mxl file ...");
J2x. buildxmldoc ();
} Catch (exception e ){
E. printstacktrace ();
}
}
} Generated user. xml file <? XML version = "1.0" encoding = "UTF-8"?>
<List>
<User id = "0">
<Name> Xuehui </Name>
<Age> 28 </age>
<Sex> male </sex>
</User>
<User id = "1">
<Name> Xuehui </Name>
<Age> 28 </age>
<Sex> male </sex>
</User>
<User id = "2">
<Name> Xuehui </Name>
<Age> 28 </age>
<Sex> male </sex>
</User>
<User id = "3">
<Name> Xuehui </Name>
<Age> 28 </age>
<Sex> male </sex>
</User>
<User id = "4">
<Name> Xuehui </Name>
<Age> 28 </age>
<Sex> male </sex>
</User>
</List>
This article from the "sorrow of frost" blog, source http://maomao.blog.51cto.com/115985/22180