Step-1:
package com;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XpathExtractor {
private static int MAX_BUFFER_SIZE = 16384;
private NamespaceContext namespaceResolver;
private XPath xpath;
private DocumentBuilder builder;
private DocumentBuilderFactory domFactory;
private String itemIdXPath;
private String shipDateXPath;
private XPathExpression itemIdXPathExpression;
private XPathExpression shipDateXPathExpression;
public CopyOfInstntInvExtractor() {
xpath = XPathFactory.newInstance().newXPath();
domFactory = DocumentBuilderFactory.newInstance();
}
public NamespaceContext getNamespaceResolver() {
return namespaceResolver;
}
public void setNamespaceResolver(NamespaceContext namespaceResolver) {
this.namespaceResolver = namespaceResolver;
}
public String getItemIdXPath() {
return itemIdXPath;
}
public void setItemIdXPath(String itemIdXPath) {
this.itemIdXPath = itemIdXPath;
this.itemIdXPathExpression = this.compile(this.itemIdXPath);
}
public String getShipDateXPath() {
return shipDateXPath;
}
public void setShipDateXPath(String shipDateXPath) {
this.shipDateXPath = shipDateXPath;
this.shipDateXPathExpression= this.compile(this.shipDateXPath);
}
public void getInfo(String message) throws Exception
{
try {
builder = domFactory.newDocumentBuilder();
Document doc = builder.parse( new InputSource(new StringReader(message)));
String itemID = (String) this.itemIdXPathExpression.evaluate(doc, XPathConstants.STRING);
String shipDate = (String) this.shipDateXPathExpression.evaluate(doc, XPathConstants.STRING);
} catch (SAXException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (XPathExpressionException e) {
throw e;
}
}
private XPathExpression compile(String expression){
try {
return this.xpath.compile( expression );
} catch (XPathExpressionException e) {
String message = "Error compiling XPath Expression [" + expression + "]";
throw new RuntimeException(message, e);
}
}
}
Step-2: Spring bean configuration:
<bean id="xpathExtractor" class="com. XpathExtractor ">
<property name="shipDateXPath" value=" itemIdXPath”/>
<property name="itemIdXPath" value=" shipDate " />
</bean>
Input :xml file
Input XML file as string for the method: getInfo (-)
<?xml version="1.0" encoding="UTF-8"?>
<functionEvent >
<itemIdXPath>10000000860002</ itemIdXPath >
<shipDate>2013-03-12</shipDate>
</ functionEvent >