如何在java中使用XPath读取具有重复节点List的Xml内容

时间:2014-12-24 16:51:59

标签: java xml xpath

我的肥皂回应为

<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>

我想阅读以下代码部分

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

在java中使用XPath。我试过它如下:

            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());
	        }

但它不会给我任何结果。我也试过这个表达式 // ns1:coveragePremiumDetail [contains(ns1:coverageName,'IDV Basic')]和 // ns1:coveragePremiumDetail [starts-with(ns1:coverageName,'IDV Basic')],但没有运气。

提前致谢。

0 个答案:

没有答案