2010-06-25 23:59
浏览 120


for example we have this xml:

                <c>another hello</c>

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();

$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?

图片转代码服务由CSDN问答提供 功能建议


 &lt; body&gt  ; 
&lt; a&gt; 
&lt; b&gt; 
&lt; c&gt; hello&lt; / c&gt; 
&lt; c&gt; world&lt; / c&gt; 
&lt; / b&gt; 
&lt; / a&gt; \  n&lt; a&gt; 
&lt; b&gt; 
&lt; c&gt;另一个问候&lt; / c&gt; 
&lt; c&gt;世界&lt; / c&gt; 
&lt; / b&gt; 
&lt; / a&gt; 
&lt;  ; / body&gt; 

通过Xpath查询我们可以找到所有“B”-tags。 但是我们需要在每个找到的“B”-tag中找到所有“C”-tags。 我写了这段代码:

  $ dom = new DOMDocument(); \  n $ dom-&gt; loadXML($ xml); 
 $ xpath = new DOMXPath($ dom); 
 $ btags = $ xpath-&gt; query(“// b”); 
foreach(  $ btags为$ b)
 $ ctags = $ xpath-&gt; query(“/ b / c”,$ b); 
 foreach($ ctags as $ c){
 echo $ c-&gt  ; nodeValue; 

但它不起作用。 可以使用XPath查询执行此操作吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dsn5510 2010-06-26 00:57

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

    打赏 评论
  • dongliyan7318 2010-06-26 00:12

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

    打赏 评论
  • duandang6352 2012-08-14 20:43

    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.

    打赏 评论

相关推荐 更多相似问题