I am using PostgreSQL 9, that adopts XPath-1 for the SQL/XML standard compliance.
This query is ok, returns the expected data:
SELECT xpath('//img',xhtm) FROM t
but this other one, to count img elements, returns empty (!),
SELECT xpath('count(//img)',xhtm) FROM t
NOTE 1: a xhtm
field content sample,
<html><p>Hello! <img src="1.png"/></p><img src="2.jpg"/></html>
NOTE 2: of course array_length(xpath('//img',xhtm),1)
show the count result, but it is not a XPath counting.
NOTE 3: I don't know if it is a generic SQL/XML peculiarity, or a PosgreSQL Server 9.0.5 specific bug/problem.
EDIT: As I noted in the comments below, and as indicated in this SO Answer, this issue was apparently addressed in Postgresql 9.2. That answer states:
With PostgreSQL 9.2 the documentation suddenly has one more sentence covering the xpath function:
If the XPath expression returns a scalar value rather than a node set, a single-element array is returned.
Just what I need! So in relation to the question another valid answer is: Upgrade to PostgreSQL 9.2.
Below is the rest of my original answer:
This seems to be a known limitation in Postgresql's xpath()
function - only expressions that evaluate to a node-set return anything; XPath expressions that would return a scalar value just return an empty array.
Some Google searches reveal some discussion about this about 2 years ago primarily from a person named Florian Pflug:
He has developed a patch that supposedly fixes the issue and that is attached to the following thread (though I'm not entirely sure this is the latest version):
http://www.postgresql.org/message-id/FC60A4F5-5560-438C-97E8-B6D1FDE1CC2B@phlo.org
There does seem to be some discussion about the pros and cons of his patch, so I'd suggest reading through these threads to be aware of what is involved:
http://www.postgresql.org/message-id/201106291957.04251.rsmogura@softperience.eu http://www.postgresql.org/message-id/201106291934.23089.rsmogura@softperience.eu