Generating XML format files from Java code

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.