答案是您需要正确使用名称空间和名称空间前缀:
首先,
documentBuilderFactory在使用名称空间之前先调用它,以使名称空间可识别:
factory.setNamespaceAware(true);
然后执行此 *** 作以检索所需的值:
XPathFactory xPathfactory = XPathFactory.newInstance();XPath xpath = xPathfactory.newXPath();xpath.setNamespaceContext(new NamespaceContext() { @Override public String getNamespaceURI(String prefix) { if (prefix.equals("soap")) { return "http://www.w3.org/2003/05/soap-envelope"; } if (prefix.equals("zmb")) { return "urn:zimbra"; } return XMLConstants.NULL_NS_URI; } @Override public String getPrefix(String namespaceURI) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Iterator getPrefixes(String namespaceURI) { throw new UnsupportedOperationException("Not supported yet."); }});XPathexpression expr = xpath.compile("/soap:Envelope/soap:Header/zmb:context/zmb:session");String sessionId = (String)expr.evaluate(doc, XPathConstants.STRING);
您可能需要在文件开头添加一行以导入NamespaceContext类:
import javax.xml.namespace.NamespaceContext;
http://ideone.com/X3iX5N
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)