0

I want to query an XML via XPath. This XML has a namespace declared. I 've read that a NameContext on the XPath object has to be set and namespace awareness in the document factory should be enabled.

But the output in the getNamespaceURI(#String) method is never print. What I'm doing wrong?

String xpathStr = ... //some string

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document document = builder.parse(settlementFile);

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath(),
xpath.setNamespaceContext(new NamespaceContext() {

     public String getNamespaceURI(String prefix) {
        System.out.println("I'm here");      
        ... //do some work 
    }

    public String getPrefix(String uri) {
        throw new UnsupportedOperationException();
    }

    public Iterator getPrefixes(String uri) {
        throw new UnsupportedOperationException();
    }
});

XPathExpression xpathExpression = xpath.compile(xpathStr);
String result = xpathExpression.evaluate(document);
Cœur
  • 37,241
  • 25
  • 195
  • 267
Pirth
  • 27
  • 2
  • 8
  • Please provide minimal but complete code snippets allowing us to reproduce the problem. It is rather pointless to tell us you are dealing with namespaces but not to show any details of the XML nor the XPath with the namespaces. – Martin Honnen Feb 28 '17 at 14:46
  • I'm refering to the following question: [link](http://stackoverflow.com/questions/6390339/how-to-query-xml-using-namespaces-in-java-with-xpath). My XML starts with ` ...` As far as I've understood it, the XPath doesn't need anything namespace spefice, when I use the above construct. When I remove the 'xmlns' part, then the evaluation works. – Pirth Feb 28 '17 at 15:03
  • Assuming the Oracle JRE the default Java JAXP XPath support is for XPath 1.0 and there for sure, in your XPath expression, you have to use a prefix bound to that namespace e.g. `/rp:Report/rp:Details/rp:Data` and then your `getNamespaceURI` has to return the string `http://com/company/report` for the prefix `rp`. You can of course choose any prefix you want, but your XPath code has to use a prefix and your context has to return the matching URI for that prefix. – Martin Honnen Feb 28 '17 at 16:09
  • Thanks you helped me a lot. I didn't really get the namespace concept. – Pirth Mar 06 '17 at 13:50

0 Answers0