Aim:
To create simple DOM parser to parse
XML document
Algorithm:
- Get a
document builder using document builder factory and parse the xml file to
create a DOM object
- Get a
list of employee elements from the DOM
- For
each employee element get the id, name, age and type. Create an employee
value object and add it to the list
- At the
end iterate through the list and print the employees to verify we parsed
it right.
Program:
DomParserExample.java
import
java.io.IOException;
import
java.util.ArrayList;
import
java.util.Iterator;
import
java.util.List;
import
javax.xml.parsers.DocumentBuilder;
import
javax.xml.parsers.DocumentBuilderFactory;
import
javax.xml.parsers.ParserConfigurationException;
import
org.w3c.dom.Document;
import
org.w3c.dom.Element;
import
org.w3c.dom.NodeList;
import
org.xml.sax.SAXException;
public class
DomParserExample {
//No generics
List myEmpls;
Document dom;
public DomParserExample(){
//create a list to hold
the employee objects
myEmpls = new
ArrayList();
}
public void runExample() {
//parse the xml file and
get the dom object
parseXmlFile();
//get each employee
element and create a Employee object
parseDocument();
//Iterate through the
list and print the data
printData();
}
private void parseXmlFile(){
//get the factory
DocumentBuilderFactory
dbf = DocumentBuilderFactory.newInstance();
try {
//Using
factory get an instance of document builder
DocumentBuilder
db = dbf.newDocumentBuilder();
//parse
using builder to get DOM representation of the XML file
dom =
db.parse("employees.xml");
}catch(ParserConfigurationException
pce) {
pce.printStackTrace();
}catch(SAXException se)
{
se.printStackTrace();
}catch(IOException ioe)
{
ioe.printStackTrace();