How to the read content of Xml having duplicate node List using XPath in java



I have a soap response as





<soapenv:Body>
<getMotorPremiumResponse xmlns="">
<ns1:getMotorPremiumReturn xmlns:ns1="">
<ns1:totalODPremium>4247.34</ns1:totalODPremium>
<ns1:discountLoadingAmt>-1268.69</ns1:discountLoadingAmt>
<ns1:discountLoading>-23.00</ns1:discountLoading>
<ns1:premiumPayable>6153.22</ns1:premiumPayable>
<ns1:gst xsi:nil="true"/>
<ns1:totalTPPremium>1229.00</ns1:totalTPPremium>
<ns1:serviceTax>676.88</ns1:serviceTax>
<ns1:totalPremimAfterDiscLoad>5476.35</ns1:totalPremimAfterDiscLoad>
<ns1:totalPremium>6745.03</ns1:totalPremium>
<ns1:coveragePremiumDetail>
<ns1:coveragePremium>0.00</ns1:coveragePremium>
<ns1:coverageName>RPI</ns1:coverageName>
<ns1:tpPremium xsi:nil="true"/>
<ns1:odPremium xsi:nil="true"/>
</ns1:coveragePremiumDetail>
........
........
<ns1:coveragePremiumDetail>
<ns1:coveragePremium xsi:nil="true"/>
<ns1:coverageName>IDV Basic</ns1:coverageName>
<ns1:tpPremium>1129.00</ns1:tpPremium>
<ns1:odPremium>5516.03</ns1:odPremium>
</ns1:coveragePremiumDetail>
.........
.........
</ns1:getMotorPremiumReturn>
</getMotorPremiumResponse>
</soapenv:Body>



I want to read the below section of code





<ns1:tpPremium>1129.00</ns1:tpPremium>
<ns1:odPremium>5516.03</ns1:odPremium>



using XPath in java. I have tried it as below:





DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(filePath);
XPathFactory xpathfactory = XPathFactory.newInstance();
XPath xpath = xpathfactory.newXPath();
XPathExpression expr = xpath.compile("//ns1:coveragePremiumDetail[ns1:coverageName='IDV Basic']/ns1:tpPremium/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}



But it doesn't returns me any result. I have also tried the expression as //ns1:coveragePremiumDetail[contains(ns1:coverageName,'IDV Basic')] and //ns1:coveragePremiumDetail[starts-with(ns1:coverageName,'IDV Basic')], but no luck.


Thanks in advance.


No comments:

Post a Comment