2011-11-16 238 views
1

我嘗試使用xpath解析SOAP響應,該響應位於某些響應消息代碼的下面。使用XPath解析soap響應消息

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<soapenv:Body> 
<ns1:Get__CompIntfc__CI_PERSONAL_DATAResponse 
xmlns:ns1="http://xmlns.oracle.com/Enterprise/Tools/schemas/M985361.V1"> 
<ns1:PROP_EMPLID>AA0001</ns1:PROP_EMPLID> 
<ns1:PROP_LAST_NAME>Adams</ns1:PROP_LAST_NAME><ns1:PROP_FIRST_NAME>Kimberly</ns1:PROP_FIRST_NAME> 
</ns1:Get__CompIntfc__CI_PERSONAL_DATAResponse > 
</soapenv:Body> 
</soapenv:Envelope> 

我嘗試解析它像...

DocumentBuilderFactory domFactory =DocumentBuilderFactory.newInstance(); 
    domFactory.setNamespaceAware(true); 
    DocumentBuilder builder = domFactory.newDocumentBuilder(); 
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    response.writeTo(out); 
InputStream is = new ByteArrayInputStream(out.toByteArray()); 
Document doc = builder.parse(is); 
     XPathExpression expr = xpath.compile("//ns1:PROP_EMPLID/text()"); 
      Object res = expr.evaluate(doc, XPathConstants.NODESET); 
      NodeList nodes = (NodeList) res; 
    for (int i = 0; i < nodes.getLength(); i++) { 
    System.out.println(nodes.item(i).getNodeValue()); 
     } 

它不提供所需的值「AA0001」 但是當我使用xpath.compile("//*/text()")它正確打印所有文本節點值。

請告訴我什麼是問題,因爲我想從響應中得到一些特定的值而不是所有的文本值。

+0

您編寫錯誤的節點名稱(包含名稱空間)。 檢查此問題:http://stackoverflow.com/questions/112601/select-element-in-a-namespace-with-xpath – Zernike

回答

1

您正在嘗試檢索由前綴ns1代表的命名空間的節點,但您的應用程序不知道什麼這個前綴代表,因爲你還沒有與任何實際的命名空間相關聯這個名字。 Java中執行此操作的方式(如@newtover所述)是使用您的xpath對象註冊javax.xml.namespace.NamespaceContext的實例。事情是這樣的:

xpath.setNamespaceContext(namespaces); 

不幸的是,沒有此接口的默認實現。你需要推出自己的。一個完整的例子可以在這裏找到:

...或者按照@ newtover的鏈接。