The example in this article describes the Java method for generating XML format files. Share to everyone for your reference, specific as follows:
This demonstrates using Java to generate XML format files
The jar package Jdom.jar used in the demo.
I wrote a demo for easy understanding.
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", "Tang Poetry 300"), New book ("2", "I'm in Java"),
New book ("3", "Glyph of God"), new book ("4", "Sunflower Treasure")};
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; doc = new document (root);
for (int i = 0; i < books.length; i++) {//Create node book;
Element elements = new Element ("book");
Add a child node to the book node and assign a value; 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 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 ("Generating books.xml file ..."); J2x.
Buildxmldoc ();
catch (Exception e) {e.printstacktrace ();
} System.out.println ("C:/books.xml file has been generated");
}
}
Operation effect is in My Computer C disk has a books.xml file (before this file)
Simple demo to see it clearly
I hope this article will help you with Java programming.