467,920 Members | 1,209 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,920 developers. It's quick & easy.

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

<?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
  • viewed: 1875
Share:
1 Reply
..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.

Similar topics

9 posts views Thread by netpurpose | last post: by
7 posts views Thread by Scott W Gifford | last post: by
3 posts views Thread by jmagaram | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.