tags:

views:

85

answers:

2

for example we have this xml:

<body>
        <a>
            <b>
                <c>hello</c>
                <c>world</c>
            </b>
        </a>
        <a>
            <b>
                <c>another hello</c>
                <c>world</c>
            </b>
        </a>
</body>

by Xpath query we can find all "B"-tags. But then we need to find all "C"-tags in every found "B"-tag. I wrote this code:

$dom = new DOMDocument();
$dom->loadXML($xml);

$xpath = new DOMXPath($dom);
$btags = $xpath->query("//b");

foreach ($btags as $b)
{
  $ctags = $xpath->query("/b/c", $b);
      foreach ($ctags as $c) {
        echo $c->nodeValue;
      }

}

But it doesn't work. It possible to do this with XPath query's?

A: 

You're already at the 'b' element by the time you get to the second query. What your code is looking for is "//b/b/c". Try using just "/c" in the second query instead. You could also move this into one query with "//b/c" if you aren't looking to do anything with "b".

brian
with `/c` doesn't work too :(doing all stuff with one query `//b/c` unfortunately not suitable for me, because i need to change "b", according to "c" values
cru3l
You can always retrieve the parent node with '..' for the query, since XPath is pretty much literally like working with a filesystem path.
Marc B
+2  A: 

For your second XPath, try this instead: $ctags = $xpath->query("c", $b);

This second XPath is already relative to the 'b' node...if I'm not mistaken, relative pathing in PHP XPath statements requires that you omit the leading '/'.

Robert Hui
thanks a lot! thats is right query!
cru3l