ImportJava.io.*;ImportJava.util.*;Importorg.jdom.*;Importorg.jdom.output.*; Public classXmlcreate { Public Static classAutoxml {PrivateList<string> fruit =NewArraylist<string>(); //Initialize the elements in the XML that will be displayed ... Public voidinitlist () {Fruit.add (Strawberry); Fruit.add (Orange); Fruit.add (Banana); Fruit.add (Grape); } Public voidbuildXML () {initlist (); //Create root node ...Element root =NewElement ("Fruit"); //Add the root node to the document ...Document Doc =NewDocument (root); for(inti = 0; I < fruit.size (); i++){ //Create a variety of fruit-like nodes ...Element elements =NewElement (Fruit.get (i)); //to various fruit nodes plus child nodes ... such as Price ...Elements.addcontent (NewElement ("Price"). SetText (i*10+ "Yuan")); Root.addcontent (elements); Xmloutputter Xmlout=NewXmloutputter (Formatxml ()); Try{String FileName= "Fruit.xml"; File File=NewFile ("d:\\", FileName); if(!file.exists ()) {File.createnewfile (); } xmlout.output (Doc,NewFileOutputStream ("D:\\fruit.xml")); } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } PublicFormat Formatxml () {//format the generated XML file, if not formatted, the resulting XML file will be a long line ...Format format =Format.getcompactformat (); Format.setencoding ("Utf-8"); Format.setindent (" "); returnformat; } Public Static voidMain (string[] args) {Try{autoxml mXml=NewAutoxml (); System.out.println ("Generate XML File ..."); Mxml.buildxml (); }Catch(Exception e) {e.printstacktrace (); } } } }
Creating an XML file using Jdom