我正在尝试使用Java中的以下代码评估我的xpath,但nodeList
返回null - 为什么会发生这种情况?我的XPath似乎在这里评估得很好:https://stackoverflow.com/a/46833473/436493。
爪哇
String message = "<AMUpdate><AMMessageType>AMPRICES</AMMessageType><amprice:AMPrices xmlns:amprice="http://www/am.com/am/dto/price"><Price><Currency>GBP</Currency><Country>LU</Country><BusinessLine>AMSL</BusinessLine></Price></amprice:AMPrices></AMUpdate>"
XPath xpath = XPathFactory.newInstance().newXPath();
InputSource source = new InputSource(new StringReader(message));
NodeList nodeList ((NodeList) xpath.evaluate("/AMUpdate/amprice:AMPrices/Price/*", source, XPathConstants.NODESET)).item(0).getChildNodes();
XML
<AMUpdate><AMMessageType>AMPRICES</AMMessageType><amprice:AMPrices xmlns:amprice="http://www/am.com/am/dto/price"><Price><Currency>GBP</Currency><Country>LU</Country><BusinessLine>AMSL</BusinessLine></Price></amprice:AMPrices></AMUpdate>
更新#2
我现在尝试了以下内容,但nodelist仍然返回null:
String message = "<AMUpdate><AMMessageType>AMPRICES</AMMessageType><amprice:AMPrices xmlns:amprice="http://www/am.com/am/dto/price"><Price><Currency>GBP</Currency><Country>LU</Country><BusinessLine>AMSL</BusinessLine></Price></amprice:AMPrices></AMUpdate>"
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
public String getNamespaceURI(String prefix) {
if (prefix == null) throw new NullPointerException("Null prefix");
else if ("am".equals(prefix)) return "http://www/am.com/am/dto/price";
else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI;
return XMLConstants.NULL_NS_URI;
}
// This method isn't necessary for XPath processing.
public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}
// This method isn't necessary for XPath processing either.
public Iterator getPrefixes(String uri) {
throw new UnsupportedOperationException();
}
});
InputSource source = new InputSource(new StringReader(message));
NodeList nodeList ((NodeList) xpath.evaluate("/AMUpdate/amprice:AMPrices/Price/*", source, XPathConstants.NODESET)).item(0).getChildNodes();