iwebie
HOME MOVIES TV SHOWS SPORTS GENERAL
 RSSPRIVACY
 

Java XML DOM Example
Posted by admin on July 13th, 2008

Watch over 100,000 movies and TV shows on your PC

Below is a Java Xml DOM Tutorial program to demonstrate how to work with XML using Java API

This program will illustrate the following concepts;

  • The Creation of an XML Document, element node, attribute node, comment node, processing instruction and a CDATA section
  • How to use DOM to work with XML
  • How to build a DOM Tree
  • How to write a DOM tree to a file
  • How to read a DOM tree from a file
  • How to read the Nodes of a DOM tree

This example below creates a file “Employee.xml” in the same path as that of the source code path

[sourcecode language='java']
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

class Employees {

private String gender;

private String firstName;

private String lastName;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Employees(String name, String gender, String name2) {
firstName = name;
this.gender = gender;
lastName = name2;
}

public String toString() {
return firstName + “\t” + gender + “\t” + lastName;
}

}

public class BuildXmlUsingDom {
private Document document;

public BuildXmlUsingDom() {
DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = dBF.newDocumentBuilder(); // java xml documentbuilder
document = builder.newDocument();
} catch (ParserConfigurationException parserException) {
parserException.printStackTrace();
}

Element root = document.createElement(”Employees”);
document.appendChild(root);

// add comment to XML document
Comment simpleComment = document.createComment(”Employee Details”);
root.appendChild(simpleComment);

// add Employee child elements
Node employeeNode = createEmployees(document);
root.appendChild(employeeNode);

// We can also add processing instructions and java xml cdata Sections as shown

/*
* ProcessingInstruction pi = document.createProcessingInstruction(
* “myInstruction”, “action silent”); root.appendChild(pi);
*
* CDATASection cdata = document .createCDATASection(”I can add <, >,
* and ?”); root.appendChild(cdata);
*/

// write the XML document to disk
try {

// create DOMSource for source XML document
Source xmlSource = new DOMSource(document);

// create StreamResult for transformation result
Result result = new StreamResult(new FileOutputStream(
“Employee.xml”));

// create TransformerFactory
TransformerFactory transformerFactory = TransformerFactory
.newInstance();

// create Transformer for transformation
Transformer transformer = transformerFactory.newTransformer();

transformer.setOutputProperty(”indent”, “yes”); //Java XML Indent

// transform and deliver content to client
transformer.transform(xmlSource, result);
}

// handle exception creating TransformerFactory
catch (TransformerFactoryConfigurationError factoryError) {
System.err.println(”Error creating ” + “TransformerFactory”);
factoryError.printStackTrace();
} catch (TransformerException transformerError) {
System.err.println(”Error transforming document”);
transformerError.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}

public Node createEmployees(Document document) {

// create FirstName and LastName elements
Element firstName = document.createElement(”FirstName”);
Element lastName = document.createElement(”LastName”);

// java xml text
firstName.appendChild(document.createTextNode(”Shawn”));
lastName.appendChild(document.createTextNode(”Michaels”));

// create employee element
Element employee = document.createElement(”Employee”);

// java xml attributes
Attr genderAttribute = document.createAttribute(”gender”);
genderAttribute.setValue(”M”);

// append attribute to contact element
employee.setAttributeNode(genderAttribute);
employee.appendChild(firstName);
employee.appendChild(lastName);

return employee;
}

// Function to read DOM Tree from File
public Document readingXMLFromFile() {
DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
dBF.setIgnoringComments(true); // Ignore the comments present in the
// XML File when reading the xml
DocumentBuilder builder = null;
try {
builder = dBF.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}

InputSource input = new InputSource(”Employee.xml”);
Document doc = null;
try {
doc = builder.parse(input);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return doc;

}

/*
* Employee.xml
*
* Shawn
* Michaels

*
*/

public ArrayList CreateListOfObjects(Document doc) {
ArrayList employeesList = new ArrayList();

Element root = doc.getDocumentElement();

// Retrieve the list of Empolyee Nodes

NodeList employeeList = root.getElementsByTagName(”Employee”);

for (int i = 0; i < employeeList.getLength(); i++) {
Element employeeElement = (Element) employeeList.item(i);
String gender = employeeElement.getAttribute("gender");
// java xml nodelist
NodeList firstNameList = employeeElement
.getElementsByTagName("FirstName");
Element firstNameElement = (Element) firstNameList.item(0);
Text firstNameText = (Text) firstNameElement.getFirstChild();
String fName = firstNameText.getNodeValue();

NodeList lastNameList = employeeElement
.getElementsByTagName("LastName");
Element lastNameElement = (Element) lastNameList.item(0);
Text lastNameText = (Text) lastNameElement.getFirstChild();
String lName = lastNameText.getNodeValue();

Employees emp = new Employees(fName, gender, lName);
employeesList.add(emp);

}

return employeesList;
}

public static void main(String args[]) {
BuildXmlUsingDom buildXmlUsingDom = new BuildXmlUsingDom();
System.out
.println("Processing Employee.xml to create Employee Objects");
Document doc = buildXmlUsingDom.readingXMLFromFile();
ArrayList empList = buildXmlUsingDom
.CreateListOfObjects(doc);
System.out.println(”The Employee Objects are”);
for (int i = 0; i < empList.size(); i++) {
System.out.println(empList.get(i));
}

}
}

[/sourcecode]

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller

Leave a Reply

Most Popular

Watch over 100,000 movies and TV shows on your PC
Recent Posts

  • Watch Dexter Season 4 Episode 9 | Dexter Hungry Man Online Video
  • Californication Season 3 Episode 9 | Watch Mr. Bad Example Full Episode
  • Watch The Amazing Race Season 15 Episode 9 | The Amazing Race s15e09 Full Video
  • English Premier League | Watch Aston Villa vs Burnley Streaming Live
  • Stargate Universe Season 1 Episode 9 | Watch Stargate Universe s01e09 Life Video Online
  • Smallville Season 9 Episode 9 | Watch Smallville s09e09 Pandora Online Free
  • Monk Season 8 Episode 14 | Watch Mr. Monk and the Badge Streaming Video
  • Community Episode 10 | Watch Community s01e10 Environmental Science Stream Online
  • Watch It’s Always Sunny in Philadelphia Season 5 Episode 10 Full Episode
  • Survivor: Samoa Episode 10 | Watch Survivor s19e10 The Day of Reckoning Free Online
Archives

  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • September 2008
  • August 2008
  • July 2008
  • June 2008
Powered by WordPress