Friday, March 4, 2011

Simple XML Parser in Java using DOM that parses all types of XML files

Hi,

After a long time I came up withan update. Following is the program that parses all types of xml files and gives the value in the elements of the xml. Actually there are two types of XML parsers in Java. DOM(Document Object Model) and SAX(Simple API for XML). DOM is used for simple XML files and SAX is used for sequential xml files.

Now I am going to explain about DOM Parser. The following are steps involved to use DOM parser.
  • Get a DOM object using Document Builder Factory to parse XML file.
  • Get a list of all parent elements in the XML file.


import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;

public class ParseXMLFile {
private final static String xmlFileName = "D:\\srikanth\\Java\\JavaXMLPArser\\XMLFile1.xml";

/** Creates a new instance of ParseXMLFile */
public ParseXMLFile() {
// parse XML file -> XML document will be build
Document doc = parseFile(xmlFileName);
// get root node of xml tree structure
Node root = doc.getDocumentElement();
// write node and its child nodes into System.out
writeDocumentToOutput(root, 0);
}

/**
* Returns element value
*
* @param elem
* element (it is XML tag)
* @return Element value otherwise empty String
*/
public final static String getElementValue(Node elem) {
Node kid;
if (elem != null) {
if (elem.hasChildNodes()) {
for (kid = elem.getFirstChild(); kid != null; kid = kid
.getNextSibling()) {
if (kid.getNodeType() == Node.TEXT_NODE) {
return kid.getNodeValue();
}
}
}
}
return "";
}

private String getIndentSpaces(int indent) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < indent; i++) { buffer.append(" "); } return buffer.toString(); } /** * Writes node and all child nodes into System.out * * @param node * XML node from from XML tree wrom which will output statement * start * @param indent * number of spaces used to indent output */ public void writeDocumentToOutput(Node node, int indent) { // get element name String nodeName = node.getNodeName(); // get element value String nodeValue = getElementValue(node); // get attributes of element NamedNodeMap attributes = node.getAttributes(); System.out.println(getIndentSpaces(indent) + "NodeName: " + nodeName + ", NodeValue: " + nodeValue); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); System.out.println(getIndentSpaces(indent + 2) + "AttributeName: " + attribute.getNodeName() + ", attributeValue: " + attribute.getNodeValue()); } // write all child nodes recursively NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { writeDocumentToOutput(child, indent + 2); } } } /** * Parses XML file and returns XML document. * * @param fileName * XML file to parse * @return XML document or null if error occured
*/
public Document parseFile(String fileName) {
System.out.println("Parsing XML file... " + fileName);
DocumentBuilder docBuilder;
Document doc = null;
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
docBuilderFactory.setIgnoringElementContentWhitespace(true);
try {
docBuilder = docBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
System.out.println("Wrong parser configuration: " + e.getMessage());
return null;
}
File sourceFile = new File(fileName);
try {
doc = docBuilder.parse(sourceFile);
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("Could not read source file: " + e.getMessage());
}
System.out.println("XML file parsed");
return doc;
}

/**
* Starts XML parsing example
*
* @param args
* the command line arguments
*/
public static void main(String[] args) {
new ParseXMLFile();
}

}

No comments:

Post a Comment