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
4 Responses to “Java XML DOM Example”
  1. Thanh Dyl Says: March 1st, 2010 at 7:14 pm

    I just think that this post was mind blowing , please add more mistress posts and I will be back all the time lol!

  2. Cameron Graeter Says: March 6th, 2010 at 9:10 am

    Fantastic post , its a wow mistress post , thank you and keep on!

  3. Hattie Seifts Says: March 10th, 2010 at 12:57 pm

    Femdom games are just my stress relief!

  4. Maribeth Skillings Says: March 17th, 2010 at 10:03 am

    Domme ladies makes me so haèèy , why dont you post some more?

Leave a Reply

Most Popular

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

  • Watch Crazy on the Outside Online Free
  • Watch It’s Complicated Full Video Online
  • Watch Leap Year Free Stream Online
  • Watch Manchester United vs Birmingham Live Stream
  • Watch Avatar Online Stream
  • Watch Nine Online Video
  • Watch Crazy Heart Full Stream
  • Modern Family Season 1 Episode 11 | Watch Modern Family s01e11 Up All Night Full Episode
  • Burnley vs Arsenal EPL | Watch Burnley vs Arsenal Live Stream
  • Watch The Princess and the Frog Online Free

Warning: include(adbottom.html) [function.include]: failed to open stream: No such file or directory in /var/www/vhosts/iwebie.com/httpdocs/wp-content/themes/iWebie/rightsidebar.php on line 20

Warning: include() [function.include]: Failed opening 'adbottom.html' for inclusion (include_path='.:/opt/lsws/lsphp5/lib/php') in /var/www/vhosts/iwebie.com/httpdocs/wp-content/themes/iWebie/rightsidebar.php on line 20
Archives

  • January 2010
  • December 2009
  • 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