Thursday, July 15, 2010

Sample XML parsing

 package sample;  

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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import com.sun.org.apache.xpath.internal.XPathAPI;

import java.io.FileNotFoundException;
import java.io.IOException;

public class XMLParser {

private static Element getRootElementFromXML() {
Element xmlRootElm = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(XML_FILE_PATH);
Document doc = builder.parse(is);
xmlRootElm = doc.getDocumentElement();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException :" + e);
} catch (IOException e) {
System.out.println("IOException :" + e);
} catch (SAXException e) {
System.out.println("SAXException :" + e);
} catch (ParserConfigurationException e) {
System.out.println("ParserConfigurationException :" + e);
}
return xmlRootElm;
}

private static Element getXmlElement(Element inRootElement, String inXpath) {
NodeList list = null;
Element element = null;
try {
list = XPathAPI.selectNodeList(inRootElement.getOwnerDocument(), inXpath);
} catch (TransformerException e) {
System.out.println("Unable to read XML : " + e);
}
if (list != null && list.getLength() > 0) {
element = (Element) list.item(0);
}
return element;
}

public static void main(String[] args) {
Element rootElement = getRootElementFromXML();
/**
* below constructed xpath : //country[@name='India']//city[@name='Chennai']
**/
String xPath = "//" + "country" + "[@name='" + "India" + "']//" + "city" +
"[@name='" + "Chennai" + "']";

Element element = getXmlElement(rootElement, xPath);
System.out.println("Code of Chennai : " + element.getAttribute("code"));
}

public static final String XML_FILE_PATH = "./src/sample/Sample.xml";
}



Sample.xml

 <?xml version="1.0" encoding="UTF-8"?>  
<countries>
<country name="India">
<city name="Delhi" code="011"/>
<city name="Mumbai" code="022"/>
<city name="Kolkata" code="033"/>
<city name="Chennai" code="044"/>
</country>
<country name="USA">
<city name="SanFrancisco" code="055"/>
<city name="Newyork" code="066"/>
<city name="Washington" code="077"/>
<city name="Florida" code="088"/>
</country>
<country name="Australia">
<city name="Sydney" code="099"/>
<city name="Melbourne" code="100"/>
<city name="Adelaide" code="111"/>
<city name="Perth" code="222"/>
</country>
</countries>