Question

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>

Code :

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

Question :
This is working perfectly when the xmlns="http://host.com/subPath" part is deleted. I wanna know how can I add xmlns="http://host.com/subPath" part to the xpathExpression to make the above work

I tried below but didn't work.

xpathExpression.addNamespace("", "http://host.com/subPath");
Was it helpful?

Solution

Solution:

.1. Add this code:

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

.2. Change:

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

to:

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

Explanation:

Xpath always treats any unprefixed element name as belonging to "no namespace".

Therefore when evaluating the XPath expression:

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

the Evaluator tries to find a wmHotelAvailResponse element that is in "no namespace" and fails because the only wmHotelAvailResponse element in the document belongs to the "http://host.com/subPath" namespace.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top