Skip to Content
0
May 14, 2016 at 02:43 PM

Using XPath in Java Mapping

277 Views

Hi Guys,

I am using XPath in my Java Mapping and unfortunately not getting out from the node. Please find piece of code below using which I am extracting Value from node.

DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();

DocumentBuilder db=factory.newDocumentBuilder();

XPathFactory xfactory=XPathFactory.newInstance();

XPath xpath=xfactory.newXPath();

String exp=null;

InputSource is=new InputSource();

NodeList nl=null;

Node node=null;

ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());

Document doc=db.parse(bis);

exp= "/ns0:MT_Source_JM/Record//Employee[2]/text()";

node=(Node)xpath.evaluate(exp,doc,XPathConstants.NODESET);

System.out.println("XPath Value=["+node.getNodeName()+"]");

}

catch(Exception e)

{

e.printStackTrace();

}

My XML is below

<ns0:MT_Source_JM xmlns:ns0="http://aa.com/test">

<Record>

<Employee id="1">

<age>29</age>

<name>Pankaj</name>

<gender>male</gender>

<role>Java Developer</role>

</Employee>

<Employee id="2">

<age>35</age>

<name>Lisa</name>

<gender>male</gender>

<role>CEO</role>

</Employee>

</Record>

</ns0:MT_Source_JM>

I need your help in executing this java code through which I can access node value through Xpath or help me with links where I can find help.

Regards,

Shankul