简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM