0

I am trying to evaluate my xpath with the following code in Java, but nodeList returns null - why does this happen? My XPath seems to be evaluating pretty well here: https://stackoverflow.com/a/46833473/436493.

Java

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>

Update #2

I've now tried the following but nodelist still returns 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();
methuselah
  • 12,766
  • 47
  • 165
  • 315
  • Duplicate of [**How does XPath deal with XML namespaces?**](https://stackoverflow.com/questions/40796231/how-does-xpath-deal-with-xml-namespaces) – kjhughes Oct 19 '17 at 17:05
  • @kjhughes I have updated the question... please assist. – methuselah Oct 19 '17 at 17:18
  • Your XPath uses the `amprice` namespace prefix yet your `getNamespaceContext()` resolves `am`, not `amprice`. – kjhughes Oct 19 '17 at 19:25

0 Answers0