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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀