By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,060 Members | 1,906 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,060 IT Pros & Developers. It's quick & easy.

xpath query "//b[1]//c" gives different results when b is nested inanother tag

P: n/a
<?php
$content = '
<a>
<d>
<b>
<c/><c/>
</b>
</d>
<b>
<c/><c/><c/>
</b>
<b>
<c/>
</b>
</a>';
$content = '
<a>
<b>
<c/><c/>
</b>
<b>
<c/><c/><c/>
</b>
<b>
<c/>
</b>
</a>';
$xml = new DOMDocument();
$xml->loadXML($content);
$xpath = new DOMXPath($xml);

$result = $xpath->query('//b[1]//c');
echo $result->length;
?>

Why is it that the first $content gives a different answer than the
second $content? Shouldn't they both be the same? Shouldn't they
both be 2? What I'm getting, instead, is that the former gives me 5
and the latter, 2. Which doesn't make any sense to me.

Any ideas?
Sep 14 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
..oO(yawnmoth)
><?php
$content = '
<a>
<d>
<b>
<c/><c/>
</b>
</d>
<b>
<c/><c/><c/>
</b>
<b>
<c/>
</b>
</a>';
$content = '
<a>
<b>
<c/><c/>
</b>
<b>
<c/><c/><c/>
</b>
<b>
<c/>
</b>
</a>';
$xml = new DOMDocument();
$xml->loadXML($content);
$xpath = new DOMXPath($xml);

$result = $xpath->query('//b[1]//c');
echo $result->length;
?>

Why is it that the first $content gives a different answer than the
second $content? Shouldn't they both be the same? Shouldn't they
both be 2? What I'm getting, instead, is that the former gives me 5
and the latter, 2. Which doesn't make any sense to me.
//b[1] matches the first 'b' child in a node set anywhere in the tree.
In the first example this matches two elements: the first 'b' is the
first child of the 'd' element, while the next 'b' is the first child of
'a'. So the result contains 5 'c' elements.

In the second example all 'b's are on the same level. Only the first one
matches your query, so you'll get 2 'c' as the result.

Your current XPath query is equivalent to this more verbose form:

/descendant-or-self::node()/b[1]//c

You could try this instead:

/descendant::b[1]//c

Micha
Sep 19 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.