2 回答

TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
我知道上次我在 java 中使用 XPath 時(shí)遇到了命名空間問(wèn)題,必須添加一個(gè) namespaceContext 才能使其工作。
如果要在 XPath 中使用soapenv 命名空間,則需要“注冊(cè)”它。你可以在下面找到我當(dāng)時(shí)所做的事情。可能不是 100% 干凈,但仍可能對(duì)您有所幫助
xpath.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
if("soapenv".equals(prefix)){
return "http://schemas.xmlsoap.org/soap/envelope/";
}else{
return null;
}
}
@Override
public String getPrefix(String namespaceURI) {
return null;
}
@Override
public Iterator getPrefixes(String namespaceURI) {
return null;
}
});
編輯:用我對(duì)您的代碼的修復(fù)進(jìn)行了測(cè)試運(yùn)行,這是您期望看到的嗎?
found node -> Header (namespace: http://schemas.xmlsoap.org/soap/envelope/)

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
這是使一切正常工作所缺少的唯一代碼行
factory.setNamespaceAware(true);
所以整個(gè)工作代碼是
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new java.io.ByteArrayInputStream(payload.getBytes()));
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
if("soapenv".equals(prefix)){
return "http://schemas.xmlsoap.org/soap/envelope/";
}else{
return null;
}
}
@Override
public String getPrefix(String namespaceURI) {
return null;
}
@Override
public Iterator getPrefixes(String namespaceURI) {
return null;
}
});
XPathExpression expr = xpath.compile("//soapenv:Envelope//soapenv:Header//text()[normalize-space()]");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
添加回答
舉報(bào)