I would like to select the value of the first “href” attribute from documents like this using XPath:
<div>
<a href="#a">
<span>foo</span>
</a>
<a href="#b">
<span>bar</span>
</a>
<a href="#c">
<span>baz</span>
</a>
</div>
However, I am only interested in those a elements that govern spans with text content “bar” or “baz”. I was hoping that I could achieve that with the following Java code:
Document document = getDocument(); // returns non-null Document
XPath xpath = XPathFactory.newInstance().newXPath();
String href = xpath.evaluate("//a[fn:matches(span, '^ba.$')]/attribute::href", document);
but whenever I’m using one of the fn: functions in an XPathExpression, I get
javax.xml.transform.TransformerException: Unknown error in XPath.
at com.sun.org.apache.xpath.internal.XPath.execute(XPath.java:363)
at com.sun.org.apache.xpath.internal.XPath.execute(XPath.java:301)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(XPathImpl.java:210)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:275)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:365)
at MyCode(MyCode.java:71)
Caused by: java.lang.NullPointerException
at com.sun.org.apache.xpath.internal.functions.FuncExtFunction.execute(FuncExtFunction.java:206)
at com.sun.org.apache.xpath.internal.axes.PredicatedNodeTest.executePredicates(PredicatedNodeTest.java:340)
[...]
Similar Exceptions are thrown when I use fn:starts-with. I’m using JDK 1.6 on GNU/Linux.
Any ideas what I’m doing wrong? Thanks!
Only the core xpath functions 1.0 (http://www.w3.org/TR/xpath/#corelib) are supported by default (as stated here: http://download.oracle.com/javase/6/docs/api/javax/xml/xpath/XPathFunctionResolver.html).
Therefore, instead of
matchesyou should usecontains(http://www.w3.org/TR/xpath/#function-contains).