Friday, August 08, 2008

read xml thru java

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLViewer {
public static void main(String[] args) {

try {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("c:/MyXMLFile.xml"));
doc.getDocumentElement().normalize();

traverseDFS(doc.getChildNodes());

} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public static void traverseDFS(NodeList nodeList) {

int lenNodes = nodeList.getLength();

for (int i = 0; i < lenNodes; i++)
{
if (nodeList.item(i).hasChildNodes()) {
System.out.println(nodeList.item(i).getNodeName());
traverseDFS(nodeList.item(i).getChildNodes());
}
else
{
if (! nodeList.item(i).getNodeValue().trim().equals("")) {
System.out.println("Value is : " + nodeList.item(i).getNodeValue());
}
}
}
}
}

No comments: