Php xpath request and xpath result

Can xpath query be used on xpath result?

+2


source to share


3 answers


In most hosting languages ​​/ frameworks (e.g. XSLT, XQuery, DOM) you can . Don't know about PHP, but it would be weird if it didn't allow it.



Of course, the result of the first request must be node-set for the future operator // to be available / resolved / successful on it.

+1


source


I did it in PHP / SimpleXML. At first I didn't realize that you are still dealing with a complete SimpleXML object, so if you start with "/ nodename" you are running as root. If you start with "nodename", you start at the beginning of the result node. Here's my example:



$parsed=simplexml_load_string($XML);

$s = '/ItemSearchResponse/Items/Item';
$items = $parsed->xpath($s);

foreach($items as $item)
  {
    $s = 'ItemAttributes/Feature';
    $features[]=$item->xpath($s);
    $s = 'ASIN';
    $asins[]=$item->xpath($s);
    $s = 'ImageSets/ImageSet[@Category="primary"]';
    $primary_img_set=$item->xpath($s);
    $s = 'MediumImage/URL';
    $medium_image_url[] = $primary_img_set[0]->xpath($s);
  }

      

+1


source


In PHP, for example, you can run a query with context, i.e. given node. So if you have a DOMNodeList as a result of the first request, you can do things like this:

$query1 = '//p';
$query2 = './a'; // do not forget the dot
$node = $xpath->query($query1)->item(0);
$result = $xpath->query($query2, $node);

      

Of course, this is a silly example because it could only have been done with one shot with the correct XPath expansion, but I believe this illustrates your question.

0


source







All Articles