This article describes the method of generating XML format files in Java. Share it for your reference, as follows:
Here is a demonstration of using Java to generate xml file
The jar package Jdom.jar used in the demo.
For the sake of easy understanding, I wrote a demo
import java.io.FileOutputStream;import java.io.IOException;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.output.Format;import org.jdom.output.XMLOutputter;public class Java2XML { Book[] books = new Book[] { new Book("1","Three Hundred Tang Poems"), new Book("2","Think in Java"), new Book("3","The Condor Heroes"), new Book("4","Sunflower Book") }; public void BuildXMLDoc() throws IOException, JDOMException { // Create the root node and set its properties; Element root = new Element("books").setAttribute("count", "4"); // Add the root node to the document; Document Doc = new Document(root); for (int i = 0; i < books.length; i++) { // Create a node book; Element elements = new Element("book"); // Add child nodes to the book node and assign values; elements.addContent(new Element("id").setText(books[i].getBook_id())); elements.addContent(new Element("name").setText(books[i].getBook_name())); // root.addContent(elements); } // Output books.xml file; // Make the xml file indent effect Format format = Format.getPrettyFormat(); XMLOutputter XMLOut = new XMLOutputter(format); XMLOut.output(Doc, new FileOutputStream("c:/books.xml")); } public static void main(String[] args) { try { Java2XML j2x = new Java2XML(); System.out.println("The books.xml file is being generated..."); j2x.BuildXMLDoc(); } catch (Exception e) { e.printStackTrace(); } System.out.println("c:/books.xml file has been generated"); }}The operation effect is that there is a books.xml file on my computer's C drive (this file was not available before)
Simple demo, you can see clearly
I hope this article will be helpful to everyone's Java programming.