Creating XML files using JavaLike most other things you want to do in Java, there exists a free library which can be used to read XML, parse XML and output an XML document. The name of the library is JDOM. To use the JDOM library to create or work with XML files, you simply need to download the package provided on their website and add it to your java class path. The following is an example of how to use the JDOM library to output a simple XML document:
import org.jdom.*;
import org.jdom.output.*; import java.io.*; public class XMLExample { public static void main(String[] args) { // Create an output stream for our file I/O FileOutputStream fOutputFile; // Create the required JDOM document and elements Document docTest = new Document(); Element eRoot = new Element("zoo"); Element eAnimals = new Element("animals"); Element eElephant = new Element("elephant"); Element eGiraffe = new Element("giraffe"); // Create the XMLOutputter which writes the XML document to the file. XMLOutputter xmlOut = new XMLOutputter(); // Set some attributes for Edward the Elephant eElephant.setAttribute("nose","long"); eElephant.setAttribute("neck","short"); eElephant.setText("Edward"); // Set some attributes for George the Giraffe eGiraffe.setAttribute("nose","short"); eGiraffe.setAttribute("neck","long"); eGiraffe.setText("George"); // Add the animals to the animals set eAnimals.addContent(eElephant); eAnimals.addContent(eGiraffe); // Add the animals set to the zoo (root XML element) eRoot.addContent(eAnimals); // Set the root element of our document docTest.setRootElement(eRoot); // Output our XML document to file try { fOutputFile = new FileOutputStream("test.xml"); xmlOut.output(docTest,fOutputFile); } catch(Exception e) { System.out.println("Failed to write out XML data."); } return; } } When you run this code, it outputs an XML file called test.xml which contains the following:
<?xml version="1.0" encoding="UTF-8"?>
<zoo> <animals> <elephant nose="long" neck="short">Edward</elephant> <giraffe nose="short" neck="long">George</giraffe> </animals> </zoo> The library is extremely flexible and contains much more functionality than I have shown here. Hopefully this code example will help some of you get a jumpstart on how to create XML documents in java. Author: DPAK Created: Nov 17 2005 Categories: Java TechByte #89 Warning: By visiting this site and/or by using any information contained herein, you agree to the Techbytes.ca terms of use. Add a comment about this TechByteIf you wish to add a comment regarding this TechByte, please use the form below. Please note that by submitting comments using this form you are allowing all of the information submitted to be visible on this website. Any comments submitted using this form will only be shown on the website if they are approved by the administrators of this site. IF APPROVED, COMMENTS MAY TAKE SEVERAL DAYS TO BE POSTED. Other TechBytes: |
|

