There is "original" XML
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header>
<context xmlns="urn:zimbra">
<session id="555">555</session>
<change token="333"/>
</context>
</soap:Header>
<soap:Body>
<AuthResponse xmlns="urn:zimbraAccount">
<lifetime>172799999</lifetime>
<session id="555">555</session>
<skin>carbon</skin>
</AuthResponse>
</soap:Body>
</soap:Envelope>
The XML is parsed in this way
// javax.xml.parsers.*
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(pathToXml);
Then I'm trying to extract session id by XPath
// javax.xml.xpath.*;
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
// next xpath does not work with Java and online xpath tester
//XPathExpression expr = xpath.compile("/soap:Envelope/soap:Header/context/session/text()");
// this xpath works with online xpath tester but does not with in Java
XPathExpression expr = xpath.compile("/soap:Envelope/soap:Header/*[name()='context']/*[name()='session']/text()");
String sessionId = (String)expr.evaluate(doc, XPathConstants.STRING);
Tested here http://www.xpathtester.com/xpath/678ae9388e3ae2fc8406eb8cf14f3119
When the XML is simplified to this
<Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<Header>
<context>
<session id="555">555</session>
<change token="333"/>
</context>
</Header>
<Body>
<AuthResponse xmlns="urn:zimbraAccount">
<lifetime>172799999</lifetime>
<session id="555">555</session>
<skin>carbon</skin>
</AuthResponse>
</Body>
</Envelope>
This XPath does its job
XPathExpression expr = xpath.compile("/Envelope/Header/context/session/text()");
How to extract session id from "original" XML with Java?
UPDATE: JDK 1.6