Xpath query unexpectedly returns 0 in Java/groovy, works in other interpreter



I'm trying to create a Cucumber step definition in Groovy that finds a certain node in an XML document (a Solr search result) by the value of a mandatory 'url' tag and returns this node's position in the list of results.


This is my step definition:



Then(~'^I will see the position of this url: "([^"]*)"$') { String text ->

pageSource = browser.getPageSource()

//Prints the position of the relevant search result
def xpathString = "count(/response/result/doc/str[.='" + text + "']/parent::*/preceding-sibling::*)" //+1

builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
doc = builder.parse(new InputSource(new ByteArrayInputStream(pageSource.getBytes("utf-8"))))
expr = XPathFactory.newInstance().newXPath().compile(xpathString)
posisjon = expr.evaluate(doc)
println "The position of this result is: " + posisjon.toString()
println xpathString

}


Here's an example of the XML result I'm evaluating:



<response>
<lst name="responseHeader">
<int name="status">0</int>
<int name="QTime">75</int>
<lst name="params">
<str name="indent">true</str>
<str name="q">pris</str>
<str name="wt">xml</str>
</lst>
</lst>
<result name="response" numFound="306" start="0">
<doc>
<str name="url">/nasjonalregnskap/nokkeltall/priser-og-prisindekser</str>
<str name="id">3730</str>
<str name="tittel">Priser og prisindekser</str>
<str name="innholdstype">nokkeltallsside</str>
<date name="publiseringsdato">2010-11-23T11:35:00Z</date>
<str name="hovedemner">Nasjonalregnskap</str>
<str name="sprak">no</str>
<str name="rom">statistikk</str>
</doc>
<doc>
<str name="url">/7292/pris-forbruk-og-inntekt</str>
<str name="id">7292</str>
<str name="tittel">Pris, forbruk og inntekt</str>
<str name="innholdstype">publikasjon</str>
<date name="publiseringsdato">2002-06-13T10:00:00Z</date>
<str name="hovedemner">Befolkning</str>
<str name="sprak">no</str>
<str name="rom">statistikk</str>
</doc>
</result>
</response>


However, when I run this test (we're using Maven to build and run, so I have limited debugging options afaik) I get this output from the two println commands:



The position of this result is: 0

count(/response/result/doc/str[.='/7292/pris-forbruk-og-inntekt?fane=om']/parent::/preceding-sibling::)



However, when I evaluate this Xpath query to the exact same XML document in Altova XMLspy, I get the expected result!


Apparently I don't have enough reputation (sorry, sorry...) to post images, here's a link to a screenshot of the result in Altova XMLspy


So the question I can't figure out is: Does the Java XPathFactory evaluate xpath differently from other interpreters? Have I made a mistake or error in my implementation? The answer eludes me :)


No comments:

Post a Comment