Reputation: 87
My XML is like below:
<?xml version="1.0"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<mime-mapping>
<extension>123</extension>
<mime-type>application/vnd.lotus-1-2-3</mime-type>
</mime-mapping>
<mime-mapping>
<extension>3dml</extension>
<mime-type>text/vnd.in3d.3dml</mime-type>
</mime-mapping>
</web-app>
As you see, it has namespace so default xpath such as /web-app/mime-mapping/mime-type
will not work.
Based on my reading on various threads, I tried:
/*[local-name()='web-app']/*[local-name()='mime-mapping']/*[local-name()='mime-type']
AND
/*[name()='web-app']/*[name()='mime-mapping']/*[name()='mime-type']
AND
/*[name()='web-app' and namespace-uri()='http://java.sun.com/xml/ns/javaee']/*[name()='mime-mapping' and namespace-uri()='http://java.sun.com/xml/ns/javaee']/*[name()='mime-type' and namespace-uri()='http://java.sun.com/xml/ns/javaee']
But none seem to work. I am testing in http://www.freeformatter.com/xpath-tester.html. Also, I am testing in my tool which requires XPath 1.0 and it does not recognize any of the above either.
Any pointers?
Upvotes: 1
Views: 2939
Reputation: 111571
Your XPath is fine.
It is your tool (http://www.freeformatter.com/xpath-tester.html) that is the problem.
Do not use http://www.freeformatter.com/xpath-tester.html with XML that has a default namespace. It is noncompliant. You can see this in the error message that they post for your XML:
The default (no prefix) Namespace URI for XPath queries is always '' and it cannot be redefined to 'http://java.sun.com/xml/ns/javaee'.
Compliant XPath processors will return
<mime-type xmlns="http://java.sun.com/xml/ns/javaee">application/vnd.lotus-1-2-3</mime-type>
<mime-type xmlns="http://java.sun.com/xml/ns/javaee">text/vnd.in3d.3dml</mime-type>
for your XPath, as expected.
Alternatively, and preferably, follow best practices and define a namespace prefix for the default namespace:
j="http://java.sun.com/xml/ns/javaee"
and use it in the XPath rather than local-name()
:
/j:web-app/j:mime-mapping/j:mime-type
to get the same result properly without skirting namespaces.
Unfortunately, you cannot define a namespace prefix on the Freeformatter site, but you can on http://www.xpathtester.com/xpath as well as with most XPath libraries.
Upvotes: 2