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>

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");
ironwood
  • 8,936
  • 15
  • 65
  • 114

1 Answers1

2

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.

Community
  • 1
  • 1
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
  • Thank you very much Dimitre. It works for me. But here I must add this x namespace prefix for every child node of x:wmHotelAvailResponse in subsequent XPathExpressions right? eg x:OTA_HotelAvailRS – ironwood Aug 21 '12 at 09:32
  • @NamalFernando, Right, any element name that belongs to the default namespace must be prefixed in the XPath expression -- otherwise (if specified unprefixed), XPath treats this as request to select this name in "no namespace" and there isn't such element name in "no namespace" in the XML document -- therefore the expression selects no nodes at all. – Dimitre Novatchev Aug 21 '12 at 11:11