What is the difference between DOMXPath :: evaluation and DOMXPath :: query?

Trying to decide which is more suitable for my use case ...

After comparing the documentation for these methods, my vague understanding of evaluate returns a typed result, but query does not. In addition, the query example includes a loop through many results, but evaluate example involves one typed result.

Still not much wiser! Can someone explain (as close as possible to layman terms) when you will use one or the other - for example. will there be multiple / single results mentioned above?

+6
source share
2 answers

DOMXPath :: query () only supports expressions that return a list of nodes. DOMXPath :: evaluation () supports all valid expressions. The official method is also called the evaluation method (): http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathEvaluator

Select all p elements inside the div : //div//p

Select all href attributes in a elements of the current document: //a/@href

You can use the string() function to pass the first element of the node list to a string. This will not work with DOMXpath :: query ().

Select the document title text: string(/html/head/title)

There are other functions and operators that will change the type of the result of an expression. But it is always unequivocal. You will always know what type of result.

+7
source

query will return a DOMNodeList regardless of your actual XPath expression. This suggests that you do not know what the result may be. Thus, you can iterate over the list and check the node type of nodes and do something based on this type.

But query not limited to this use case. You can still use this when you know what type you will get. In the future, what you wanted to achieve may be more understandable, and therefore easier to maintain.

evaluate , on the other hand, gives you exactly the type you choose. As the examples show:

 $xpath->evaluate("1 = 0"); // FALSE $xpath->evaluate("string(1 = 0)"); // "false" 

As it turned out, the choice of attributes //div/@id or text nodes //div/text() still gives a DOMNodeList instead of strings. Therefore, potential use cases are limited. You would have to enclose them in string : string(//div/@id) or text nodes string(//div/text()) .

The main benefit of evaluate is that you can get lines from a DOMDocument with fewer lines of code. Otherwise, it will return the same result as query .

ThW's answer is correct that some expressions will not work with query :

 $xpath->query("string(//div/@id)") // DOMNodeList of length 0 $xpath->evaluate("string(//div/@id)") // string with the found id 
+4
source

Source: https://habr.com/ru/post/969664/


All Articles