XML:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<wmHotelAvailResponse xmlns="http://host.com/subPath">
<OTA_HotelAvailRS Version="1.001">
</OTA_HotelAvailRS>
</wmHotelAvailResponse>
</soap:Body>
</soap:Envelope>
代码:
String xpathString = "/soap:Envelope/soap:Body/wmHotelAvailResponse/OTA_HotelAvailRS";
AXIOMXPath xpathExpression = new AXIOMXPath(xpathString);
xpathExpression.addNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
xpathExpression.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xpathExpression.addNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
OMElement rsMsg = (OMElement)xpathExpression.selectSingleNode(documentElement);
String version = rsMsg.getAttribute(new QName("Version")).getAttributeValue();
问题:
当删除xmlns="http://host.com/subPath"
部分时,此功能非常有效。我想知道如何将xmlns="http://host.com/subPath"
部分添加到xpathExpression
以完成上述工作
我在下面试过但没有用。
xpathExpression.addNamespace("", "http://host.com/subPath");
答案 0 :(得分:2)
<强>解决方案强>:
0.1。添加以下代码:
xpathExpression.addNamespace("x", "http://host.com/subPath");
0.2。变化:
String xpathString = "/soap:Envelope/soap:Body/wmHotelAvailResponse/OTA_HotelAvailRS";
以强>:
String xpathString = "/soap:Envelope/soap:Body/x:wmHotelAvailResponse/x:OTA_HotelAvailRS";
<强>解释强>:
Xpath始终将任何未加前缀的元素名称视为属于“no namespace”。
因此在评估XPath表达式时:
/soap:Envelope/soap:Body/wmHotelAvailResponse/OTA_HotelAvailRS
Evaluator尝试查找“no namespace”中的wmHotelAvailResponse
元素并失败,因为文档中唯一的wmHotelAvailResponse
元素属于“http://host.com/subPath”命名空间。