dsj83686 2013-05-24 17:14
浏览 75
已采纳

获取与Xpath表达式匹配的元素的“面包屑”(在PHP中)

I have an XML structure in which certain elements have been marked by attributes, like so:

<a>
   <b1>
      <c1 special="yes" />
   </b2>
   <b2>
      <c2 />
   </b2>
</a>

I would like to locate the paths (or "breadcrumbs") for all elements matched by the attributes. In the above example:

//*[@special="yes"]

Result:
/a/b1/c1

I don't care about the values at all, just the list of paths to all "special" elements would suffice.

Edit: forgot to mention that I am looking for a solution in PHP, as there probably is not solution provided by XPath mechanisms.

Thanks.

  • 写回答

4条回答 默认 最新

  • doulei3488 2013-05-24 23:08
    关注

    You can use the ancestor-axis to fetch this path.

    The Fully-Fledged Xpath 2.0 Solution

    This will return a path for the current element. More on this solution in my answer to a similar question where XPath 2.0 was fine. If you append //*[@special="yes"]/, it will return all pathes for the "special" elements.

    string-join(
      (
        '',
        (
          .//ancestor-or-self::*/name(),
          concat("@", .//ancestor-or-self::attribute()/name())
        )
      ),
      '/'
    )
    

    You can remove all newlines if you prefer, but it's easier to understand when nicely wrapped.

    Getting Your Hands Dirty

    Sadly, PHP does not support XPath 2.0 out-of-the-box and you will have to do the looping and concatenation stuff in PHP, but still can use the ancestor-axis.

    Building upon @Rolando Isidoro solution, this will make the "main" loop of his code both more elegant and efficient (although the improvement is minor and probably only noticeable in very large documents with very deep structure):

    foreach ($nodes as $node) {
        $breadcrumbs[$nodeCount] = array();
    
        // Returns all nodes on ancestor path in document order
        foreach ($node->xpath('ancestor-or-self::*') as $axisStep) {
          // So all we need to do is append the name at the end of the array
          $breadcrumbs[$nodeCount][] = $axisStep->getName();
        }
    
        $nodeCount++;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊