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 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误