duanhuo3392 2018-09-05 04:11
浏览 59
已采纳

PHP XMLNode,DOMnode Xpath选择谓词的孙子属性值

I have some xml

<div> First Element
 <div>
  <level3 name="fred">
  </level3>
 </div>
</div>
<div> Second Element
 <div>
  <level3 name="dave">
  </level3>
 </div>
</div>
<div> Third Element
 <div>
  <level3 name="jim">
  </level3>
 </div>
</div>
<div> Fifth Element
 <div>
  <level3 name="mike">
  </level3>
 </div>
</div>

I want to extract the xml (as a string, including the xml tags) from a specific top level div element based in its grandchilds name at level3.

So to get the top div above the level3 node with the name of jim I have been looking at things like:

$sname="jim";
$spath = new DOMXPath($doc);
// Find a div with a child div with a level3 with a matching attribute name. 
$spexp = "//div[./div/level3[contains(@name,\"$sname\")]]";
$story = $spath->evaluate("$spexp");
echo $story->item(0)->nodeValue . "
";

I have tried various combinations - including 'exists' in the predicate which I am sure is basic xslt, but not in PHP(!).

I have googled loads... but predicates going down past the immediate level hasn't come up, and it seems PHP's xpath has its own flavour, so general XPath stuff isn't always useful.

展开全部

  • 写回答

1条回答 默认 最新

  • duandunzhuo3234 2018-09-05 04:19
    关注

    The XPath was OK, this just removes the first bit inside the first [ as it's not needed.

    To output the XML, you need to use saveXML() with the node you want to export all of the XML tags as well...

    $sname="jim";
    $spath = new DOMXPath($doc);
    // Find a div with a child div with a level3 with a matching attribute name.
    $spexp = "//div[div/level3[contains(@name,\"$sname\")]]";
    $story = $spath->evaluate("$spexp");
    echo $doc->saveXML($story->item(0)). "
    ";
    

    Gives...

    <div> Third Element
     <div>
      <level3 name="jim">
      </level3>
     </div>
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 没输出运行不了什么问题
  • ¥20 输入import torch显示Intel MKL FATAL ERROR,系统驱动1%,: Cannot load mkl_intel_thread.dll.
  • ¥15 点云密度大则包围盒小
  • ¥15 nginx使用nfs进行服务器的数据共享
  • ¥15 C#i编程中so-ir-192编码的字符集转码UTF8问题
  • ¥15 51嵌入式入门按键小项目
  • ¥30 海外项目,如何降低Google Map接口费用?
  • ¥15 fluentmeshing
  • ¥15 手机/平板的浏览器里如何实现类似荧光笔的效果
  • ¥15 盘古气象大模型调用(python)
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部