Java method for generating XML format Files _java

Source: Internet
Author: User

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.

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.