Friday, 13 November 2015

Create Xml Document Using Jdom

JDOM is an open source implementation of an XML document manipulation library for the Java programming language. JDOM is bundled with most integrated development environments for Java software development and is available free of charge directly from the JDOM website. JDOM was first invented in early 2000, and provides a consistent means for creating, writing, reading, and manipulating XML data. A common task for Java programmers is to create an XML document using JDOM.


Instructions


1. Open a new file in your text editor or IDO and type the following package import statements at the top of the file to include the JDOM libraries with your program:


import org.jdom.Document;


import org.jdom.Element;


import org.jdom.output.XMLOutputter;


2. Start a new Java class that will write new XML Documents using the JDOM libraries by typing the following code after the last import statement in step 1.


public class DocWriteJDOM {


}


3. Define the method that will create a new XML document using the JDOM library by typing the following code after the { bracket in the class definition.


public Document makeJDOMDoc() throws Exception


{


Document myJDOMDoc = new Document(new Element("Kentucky"));


myJDOMDoc.getRootElement().


addContent(new Element("Wildcats").


addContent(new Element("Louisville").


setText("Cardinals")).


addContent(new Element("Memphis").


setText("Tigers")));


return myJDOMDoc;


}


4. Add a main method to the class after the closing } brackert in the makeJDOMDoc method to create the JDOM document. This example will output the document to the console window.


public static void main(String[] args) throws Exception {


DocWriteJDOM myDoc = new DocWriteJDOM ;


Document jdomDoc = myDoc.makeJDOMDoc();


new XMLOutputter().output(doc, System.out);


}

Tags: addContent Element, import jdom, using JDOM, code after, create document