XML

"Continuous effort - not strength or intelligence - is the key to unlocking our potential." ==> Winston Churchill

Name:
Location: Bangalore, India

Wednesday, April 09, 2008

Accessing data using XPATH in a XML file

We can learn 2 different ways of creating document object (getXmlParser() , getXmlParsers() ) and accessing the data from xml file using XPATH.

Error.xml
<?xml version="1.0" encoding="UTF-8"?>
<EXCEPTION_ROOT>
<EXCEPTION CODE="BENEF_1000">
<EXCEPTION_MESSAGE>
Beneficiary is not saved
</EXCEPTION_MESSAGE>
</EXCEPTION>
<EXCEPTION CODE="BENEF_1001">
<EXCEPTION_MESSAGE>
No records found
</EXCEPTION_MESSAGE>
</EXCEPTION>
</EXCEPTION_ROOT>

Error.xml
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.w3c.dom.Document;

public class Error {

private static Document doc;
private static DOMParser objDOMParser = null;
private static String fileName = "Error.xml";

public static void main(String[] args){

Error err1 = new Error();
err1.getXmlParsers();

err1.getSQLQuery("BENEF_1000");

Error err2 = new Error();
err2.getXmlParser();

err2.getSQLQuery("BENEF_1001");
}
public void getXmlParsers() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

try {
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream objInputStream = this.getClass().getResourceAsStream(fileName);
doc = builder.parse(objInputStream);
}catch(ParserConfigurationException parserException) {
}catch(SAXException saxException) {
}catch(IOException ioException) {
}catch(Exception exception){}
}
public void getXmlParser() {
try {
InputStream is = this.getClass().getResourceAsStream(fileName);
org.xml.sax.InputSource isrc = new org.xml.sax.InputSource(is);
objDOMParser = new DOMParser();
objDOMParser.parse(isrc);
doc = objDOMParser.getDocument();
} catch (Exception e) {
System.err.println(e);
}
}

public static void getSQLQuery(String queryName) {
String errorMessage = null;
try{
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
String expression ="EXCEPTION_ROOT/EXCEPTION[@CODE='"+queryName+"']/EXCEPTION_MESSAGE/text()";
XPathExpression expr = xpath.compile(expression);
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
errorMessage = nodes.item(0).getNodeValue();
System.out.println(errorMessage);
}
catch(Exception ex) {
ex.printStackTrace();
System.out.println("......Error while parsing.....");
}
}
}

0 Comments:

Post a Comment

<< Home