开发者

xpath query to xpath result of query

for example we have this xml:

<body>
        <a>
            <b>
                <c>hello</c>
                <c>world</c>
            </b>
        </a>
        <a>
            <b>
                <c>another hello&开发者_Python百科lt;/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?


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 '/'.


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".


Robert Hui is not mistaken

FYI //b selects all elements that are type b anywhere in the document but using / means to select the root node, thus /b/c is trying to select the root node b that has a child node c. The root node is the body element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜