Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.PrintWriter;
Import Javax.swing.JOptionPane;
Import org.dom4j.Document;
Import Org.dom4j.DocumentHelper;
Import org.dom4j.Element;
/**
* This type of test generates a file in XML format
* @author Guanshun
*
*/
public class Createxmlfile {
book[] books = new book[]
{
New book ("1", "300 Tang Poems"),
New book ("2", "Think in Java"),
New book ("3", "Condor"),
New Book ("4", "Sunflower Treasure")
};
public static void Main (string[] args) throws FileNotFoundException {
createxmlfile createxmlfile = new Createxmlfile ();
Createxmlfile.buildxmldoc ();
}
public void Buildxmldoc () throws FileNotFoundException {
Document dom = Documenthelper.createdocument ();
element Root=dom.addelement ("books");//Add root element
Root.addattribute ("Count", "4");
//Root.settext ("value in the middle of the Xval label");
for (int i = 0; i < books.length; i++) {
Element elements = root.addelement ("book");
elements.settext ("111111");
elements.addattribute ("id", Books[i].getid () );
elements.addattribute ("name", Books[i].getname () );
}
String xml=dom.asxml ();
System.out.println (XML);
File F=new file ("C:/xml/guanshun.xml");
printwriter pw=new printwriter (f);
pw.write (XML);
pw.close ();
joptionpane.showmessagedialog (NULL, "XML file generated, path is D:/xml.xml");
}
}
This article is from the "dream Do not Fall" blog, please be sure to keep this source http://5029900.blog.51cto.com/5019900/1605396
Generating XML format files from Java code