I have the following XML document:
<application xmlns="http://www.example.com/schemas/app-config/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.com/schemas/app-config/1.0 http://www.example.com/schemas/app-config/1.0/app-config-1.0.xsd">
<info name="Dummy Application" runningOn="Dev"/>
</application>
When I run the following code:
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("/application/info@name");
I get an XPathExpressionException on the compile method. The exception’s message is simply “null“. It looks like I’m correctly using XPath to locate the name attribute, but I’m wondering if all my XMLNS and XSI declarations are causing problems here? If not then I’m totally clueless and have no idea what’s causing this exception.
One thing – how can compile be failing before I ever associate the xpath instance with my actual Document object?!?
You simply have a syntax error in the expression
/application/info@name, the correct syntax is/application/info/@name. Note however that your XML sample has a default namespace so with XPath 1.0 the expression/application/info/@namedoes not select anything in that sample, with XPath 2.0 you would need to make sure you associate define the default namespace for the XPath evaluation. With XPath 1.0 you need to define a prefix (e.g.df) for the default namespace in your Java code and then use e.g./df:application/df:info/@name. I am not familiar with the Java XPath API so someone else needs to help with concrete code on how to set up the namespaces with an XPathNamespaceContext or similar.