0

What would be the right validation if i want to know that my XPath Query is not working..

$query_id = $xpath->query('//tr[@class="calendar_row"][@data-eventid]/@data-evenid');
if (!is_null($query_id)) {
    ...
} else {
    echo 'Invalid Query!';
}

I'm using the code above but it displays nothing even if the query cannot produce any result.

4

3 回答 3

3

So the way I understand this is you want to check for an empty list. Here is what PHP.net says about DOMXPath::query():

Returns a DOMNodeList containing all nodes matching the given XPath expression. Any expression which does not return nodes will return an empty DOMNodeList.

If the expression is malformed or the contextnode is invalid, DOMXPath::query() returns FALSE.

With that said, you must check for an empty DOMNodeList, which may not actually return FALSE when checked with a negation since it's an "Traversable" object.

Instead just use something like the following:

$query_id_entries = $xpath->query('//tr[@class="calendar_row"][@data-eventid]/@data-evenid');
if ($query_id_entries->length == 0) {
    echo "invalid query";
} else {
    foreach($query_id_entries as $query_id) {
        // ...
    }
    // Or you could do the following.
    // $query_id = $query_id_entries->item(0);
}
于 2012-12-19T15:00:40.123 回答
1

If the expression is malformed or the contextnode is invalid, DOMXPath::query() returns FALSE. So,

$query_id = $xpath->query('//tr[@class="calendar_row"][@data-eventid]/@data-evenid');
if (!($query_id)) {
    echo "invalid query";
} else {
    echo 'Valid Query!';
}

Did you mean something like this

于 2012-12-19T07:24:27.470 回答
1

it displays nothing even if the query cannot produce any result

There are many queries that cannot produce any result. An example would be

//employee[hire-date gt current-date()]

There is no way, of course, that the system can know that all employees have a hire-date in the past, so this query will simply return nothing, and you will have to figure out why.

But perhaps you mistyped "hire-date". Perhaps it should have been "hireDate" or "@hire-date"? In this case you might expect that the system would be able to spot your error. The answer is that it can, provided you use a query processor that is schema-aware, and that you take advantage of the schema awareness by telling the query processor about your schema (typically with an "import schema" declaration in the query prolog).

It can be a bit of a pain to use schema-awareness for simple ad-hoc queries, which is probably why most people don't bother. But if you are developing something complex, it can be a real help in making debugging easier - particularly for the "blank screen" problem where your query returns nothing, and there is no way of finding out why except by staring at it until the light dawns.

An example of a schema-aware query processor that uses the schema to detect errors at compile time is Saxon-EE.

于 2012-12-19T08:53:19.383 回答