The following class has methods for creating and parsing an xml document using JDom.
Code:
package in.techdive.java;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
public class XMLJDomParser
{
public static void main(String[] args)
{
XMLJDomParser xmlJDomParser = new XMLJDomParser();
String fileName = "Devices.xml";
// first create a xml document and pass the xml string to create an xml file
xmlJDomParser.createFile(xmlJDomParser.createDocument(), fileName);
// parse the same document
xmlJDomParser.parseDoc(fileName);
}
/*
* This method parses each element in the xml document and prints the text content.
*/
public void parseDoc(String fileName)
{
Document doc = null;
InputStream input = null;
SAXBuilder saxBuilder = null;
try
{
input = new FileInputStream(fileName);
saxBuilder = new SAXBuilder(false);
doc = saxBuilder.build(input);
Element root = doc.getRootElement();
parseElement(root);
}
catch (Exception e)
{
}
}
private void parseElement(Element root)
{
List<Element> lstElements = root.getChildren();
for (Element elem : lstElements)
{
if (elem.getChildren().size() > 0)
{
parseElement(elem);
return;
}
else
System.out.println(elem.getText());
}
}
/*
* This method creates an xml file using the xmlstirng and file name as arguments.
*/
public void createFile(String fileContents, String fileName)
{
File file = new File(fileName);
FileOutputStream fOut = null;
try
{
fOut = new FileOutputStream(file);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
BufferedOutputStream bf = new BufferedOutputStream(fOut);
try
{
bf.write(fileContents.getBytes());
bf.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/*
* This method creates a xml document using jdom.
*/
public String createDocument()
{
String xmlDoc = null;
try
{
Document doc = new Document(new Element("Devices"));
Element device = new Element("Device");
Element deviceId = new Element("deviceId").setText("1001");
Element deviceName = new Element("deviceName").setText("Cables Connectors");
Element productId = new Element("productId").setText("CC1084");
Element serialNo = new Element("serialNo").setText("038123-45627");
doc.getRootElement().addContent(device);
device.addContent(deviceId);
device.addContent(deviceName);
device.addContent(productId);
device.addContent(serialNo);
XMLOutputter domstream = new XMLOutputter();
domstream.output(doc, System.out);
xmlDoc = domstream.outputString(doc);
}
catch (Exception e)
{
e.printStackTrace();
}
return xmlDoc;
}
}
Bookmarks