Conditions

In addition to their surrounding hierarchical structure, nodes can also be addressed based on conditions.

<?php
// Returns all ul nodes with an id attribute node $list = $xpath->query('//ul[@id]');

// Returns all li child nodes of the ul node with an id of "thelist"
$list = $xpath->query('//ul[@id = "thelist"]/li');

// Returns the first ul node that is a descendant of the context node $list = $xpath->query('//ul[1]');

// Returns the first li child node of each ul node
$list = $xpath->query('//ul/li[1]');

// Returns all ul nodes containing an li node with the value "foobar" $list = $xpath->query('//ul[li = "foobar"]');
?>
  • Square brackets are used to delimit a conditional expression.
  • Element and attribute nodes are denoted the same way within a condition as they are outside of one. That is, elements are simply referred to by element name and attribute names are prefixed with @.
  • The = operator is used for equality comparisons. The converse, the != operator, checks for inequality. Other fairly standard comparison operators are also supported, including <, <=, >, and >=.
  • A condition comprised only of a single number is actually short for position() = # where # is the number used. position is a function that returns the position of each individual node within the current context.

© DOM Extension — Web Scraping

>>> Back to TABLE OF CONTENTS <<<
Category: Article | Added by: Marsipan (01.09.2014)
Views: 346 | Rating: 0.0/0
Total comments: 0
avatar