3

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");
4

1 回答 1

2

解决方案

.1。添加此代码:

xpathExpression.addNamespace("x", "http://host.com/subPath");

.2. 改变:

String  xpathString = "/soap:Envelope/soap:Body/wmHotelAvailResponse/OTA_HotelAvailRS"; 

String  xpathString = "/soap:Envelope/soap:Body/x:wmHotelAvailResponse/x:OTA_HotelAvailRS";  

说明

Xpath 总是将任何无前缀的元素名称视为属于“无命名空间”。

因此,在评估 XPath 表达式时:

/soap:Envelope/soap:Body/wmHotelAvailResponse/OTA_HotelAvailRS

Evaluator 尝试查找wmHotelAvailResponse“无命名空间”中的元素并失败,因为文档中的唯一wmHotelAvailResponse元素属于“http://host.com/subPath”命名空间。

于 2012-08-20T12:22:12.837 回答