Java generates XML files

Source: Internet
Author: User

The analysis will, then come to learn the students into ~

The same introduction depends on:

Import Java.io.File; Import Java.io.FileOutputStream; Import org.dom4j.Document; Import Org.dom4j.DocumentHelper; Import org.dom4j.Element; Import Org.dom4j.io.OutputFormat; import Org.dom4j.io.XMLWriter;

Note Handling Exceptions:

 Public Static void throws Exception {}

To create a tree:

Document doc = documenthelper.createdocument (); // Add root node Element books = doc.addelement ("books"); // Add child elements Element Book1 = books.addelement ("book"= book1.addelement ("title"= book1.addelement ("author") ;     = Books.addelement ("book"= book2.addelement ("title"= book2.addelement ("author");

To add properties to the corresponding node:

Book1.addattribute ("id", "001"); Title1.settext ("Harry Potter"); Author1.settext ("J K. Rowling");          Book2.addattribute ("id", "002"); Title2.settext ("Learning XML"); Author2.settext ("Erik T. Ray ");

Next comes the output, sets the encoding, and creates the File object:

OutputFormat format = outputformat.createprettyprint (); Format.setencoding ("UTF-8"New File ("Writebooks.xml");

The XMLWriter object is generated based on the File object created:

New XMLWriter (new fileoutputstream (file), format);

Finally, write the Document object that you created to the XMLWriter object:

Writer.write (DOC);

Java generates XML files

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.