/**
* Generate an XML file
* @ Throws ioexception
* @ Throws jdomexception
*/
Public void buildxmldoc () throws ioexception, jdomexception {
// Create a list of root nodes;
Element root = new element ("country ");
Root. setattribute ("code", "86 ");
Root. setattribute ("name", "China ");
// Add the root node to the document;
Document Doc = new document (Root );
Querydao Dao = new querydao ();
List <bean> provinces = Dao. queryallprovince ();
// Here, The for loop can be replaced with the result set operation for Traversing database tables;
For (bean Province: provinces ){
// Create a node user;
Element elprovince = new element ("Province ");
// Add the property ID to the province node;
Elprovince. setattribute ("name", Province. getname (). Trim ());
Elprovince. setattribute ("code", Province. GETID () + "");
// Add a subnode to the user node and assign a value to it;
List <bean> citys = Dao. querycitybyproviceid (province. GETID ());
For (bean City: citys ){
Element elcity = new element ("city ");
Elcity. setattribute ("name", city. getname (). Trim ());
Elcity. setattribute ("code", city. GETID () + "");
List <bean> countrys = Dao. querycountrybycityid (city. GETID ());
For (bean country: countrys ){
Element clcountry = new element ("County ");
Clcountry. setattribute ("name", country. getname (). Trim ());
Clcountry. setattribute ("code", country. GETID () + "");
Elcity. addcontent (clcountry );
}
Elprovince. addcontent (elcity );
}
// Add a user subnode to the parent node list;
Root. addcontent (elprovince );
}
Xmloutputter xmlout = new xmloutputter ();
Format F = format. getprettyformat ();
F. setencoding ("UTF-8 ");
Xmlout. setformat (f );
// Output the user. xml file;
Xmlout. Output (Doc, new fileoutputstream ("F:/area. xml "));
}
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
Createxml Cx = new createxml ();
Try {
Cx. buildxmldoc ();
System. Out. println ("file generated successfully! ");
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (jdomexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}