2

Can I use an xpath query on a result already obtained using xpath?

3 Answers 3

1

In most hosting languages/environments (like XSLT, XQuery, DOM) you can. Don't know about PHP, but it would be strange if it doesn't allow this.

Of course, the result of the first query must be a node-set, in order for a future "/" operator to be possible/allowed/successful on it.

Sign up to request clarification or add additional context in comments.

Comments

1

I have done it in PHP/SimpleXML. The thing that I didn't understand at first is that you're still dealing with the full SimpleXML object, so if you start with "/nodename", you're operating on root. If you start with "nodename" you are starting 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);
  }

Comments

0

In PHP, for example, you can run a query with a context, i.e. a given node. So if you have got a DOMNodeList as a result of the first query 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 have been done just in one shot with the correct XPath experssion but I believe it illustrates your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.