Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

May 13, 2010

Very Simple XML DOMParser

Sample XML :












































Java Code :


import java.io.IOException;

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 MyDOMParser {

Document dom;
public void runExample() {

//parse the xml file and get the dom object
parseXmlFile();

//get each element
parseDocument();


}


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("BOVarswaps.xml");
dom = db.parse("BOPostTrade.xml");


}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
}


private void parseDocument(){
//get the root elememt
Element docEle = dom.getDocumentElement();

//get a nodelist of elements
NodeList nl = docEle.getElementsByTagName("class");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {

//get the employee element
Element el = (Element)nl.item(i);

//get the Employee object
System.out.println("*"+el.getAttribute("name"));

NodeList propertyList = el.getElementsByTagName("property");
if(propertyList != null && propertyList.getLength() > 0 ){
for(int ii = 0 ; ii < propertyList.getLength();ii++){
Element inner = (Element)propertyList.item(ii);
System.out.println(" * "+inner.getAttribute("name"));
}

}
System.out.println("");
}
}
}


public static void main(String[] args){
//create an instance
MyDOMParser dpe = new MyDOMParser();

//call run example
dpe.runExample();
}

}

http://www.totheriver.com/learn/xml/xmltutorial.html#6

No comments: