doz15449
doz15449
2012-05-09 16:18

PHP和Xpath,根据伟大的孩子过滤结果

已采纳

Consider the following test.xml

<root>
    <parent>
        <ID>1</ID>
        <child1>Value1</child1>
        <child2>value11</child2>
        <child3>
             <grandchild>
                  <greatgrandchild>value1111</greatgrandchild>
             </grandchild>
        </child3>
    </parent>
    <parent>
        <ID>2</ID>
        <child1>value2</child1>
         <child3>
             <grandchild>
                  <greatgrandchild>value2222</greatgrandchild>
             </grandchild>
        </child3>
    </parent>
    <parent>
        <ID>3</ID>
        <child1>value3</child1>
        <child2>value33</child2>
        <child3>
             <grandchild>
                  <greatgrandchild>value3333</greatgrandchild>
             </grandchild>
        </child3>
    </parent>
    <parent>
        <ID>4</ID>
        <child1>value4</child1>
        <child2>value44</child2>
        <child3>
             <grandchild>
                  <greatgrandchild>value4444</greatgrandchild>
             </grandchild>
        </child3>
        </parent>
</root>

When I use the following for xpath '/root/parent', I can easily get the values of ID, child1, and child2.

However I do not get the values of the greatgrandchild of grandchild.

What can I do to get these values.

$query = '/root/parent'
$xQuery = $xml->xpath($query);
foreach($xQuery as $results){
    echo $results->ID;
    echo $results->child1;
    echo $results->child2;
    echo $results->greatgrandchild;
}

I would like to filter the result based on the value of greatgrandchild. I can successfully filter the results of ID and child1 and child2. I want to be getting a parent and all of its children and grandchildren and greatgrandchild based on the value of greatgrandchild.

Is this possible using xpath?

I have edited the wording of the question and used the proper test.xml as I had errors in it the first time around.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • drtsd7864 drtsd7864 9年前

    There are 2 problems in your code,

    • grandchild node is ambiguous and malformed. The closing tag of grandchild2 is grandchild which is wrong.

      This is wrong------------+
                               |  
                               v
      <grandchild2>value3333</grandchild>
      
    • $results->grandchild does not exists, rather use $results->child3->grandchild. Here Xpath returns all the parent nodes under root node as SimpleXMLElement

    To find all the parent element whose child1=value3 and grandchild1=value333 use this query.

    /root/parent[child1 = "value3" and child3/grandchild = "value333"]
    
    点赞 评论 复制链接分享

为你推荐