2013-10-11 90 views
0

獲取的SOAP Body我使用XML的XPath API在我的應用程序使用XPath和XML語言的XPath API

這是我的SOAP請求

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tes="http://testwork/"> 
     <soapenv:Header/> 
     <soapenv:Body> 
      <tes:sayHelloWorldFrom> 
      <!--Optional:--> 
      <arg0>value</arg0> 
      </tes:sayHelloWorldFrom> 
     </soapenv:Body> 
    </soapenv:Envelope> 

我想從該消息中檢索的身體,所以我想有

<soapenv:Body> 
      <tes:sayHelloWorldFrom> 
      <!--Optional:--> 
      <arg0>value</arg0> 
      </tes:sayHelloWorldFrom> 
</soapenv:Body> 

我的一段代碼看起來像

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     org.w3c.dom.Document doc = null; 
     try { 
      doc = factory.newDocumentBuilder().parse(is); 
      XPathFactory xFactory = XPathFactory.newInstance(); 
      XPath xPath = xFactory.newXPath(); 
      Object result = xPath.compile("/soapenv:Envelope/soapenv:Body").evaluate(doc, XPathConstants.NODESET); 
      NodeList nodes = (NodeList) result; 
      log.info("result " + nodes); 

但結果是result [email protected]

那麼我做錯了什麼?

回答

3

XPathConstants.NODESET指示API返回匹配查詢的結果的NodeList

當您期待可變數量的匹配時,這非常有用。你可以遍歷列表...

for (int index = 0; index < nodes.getLength(); index++) { 
    Node node = nodes.item(index); 
    //... 
} 

如果你有信心,你將只能得到一個結果(或者你只是想在第一場比賽),你可以使用XPathConstants.NODE代替

Object result = xPath.compile("/soapenv:Envelope/soapenv:Body").evaluate(doc, XPathConstants.NODE); 
Node node = (Node)result; 

更新

有可能離開做這個而不做以下,但名字空間做我的頭......

創建factory, set it's name space awareness to FALSE`後,再從搜索刪除節點名字空間方面,例如...

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
factory.setNamespaceAware(false); 
org.w3c.dom.Document doc = null; 
try { 
    doc = factory.newDocumentBuilder().parse(new File("Soap.xml")); 

    XPathFactory xFactory = XPathFactory.newInstance(); 
    XPath xPath = xFactory.newXPath(); 
    Object result = xPath.compile("/Envelope/Body").evaluate(doc, XPathConstants.NODESET); 
    NodeList nodes = (NodeList) result; 
    System.out.println("Found " + nodes.getLength() + " matches"); 
    for (int index = 0; index < nodes.getLength(); index++) { 
     Node node = nodes.item(index); 
     System.out.println(node); 
    } 
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException exp) { 
    exp.printStackTrace(); 
} 
+0

爲(INT指數= 0; index user2390742

+0

是什麼意思「無法訪問」 – MadProgrammer

+0

xPath沒有找到與您的查詢匹配的信息 – MadProgrammer