您可以使用祖先轴来获取此路径。
成熟的 Xpath 2.0 解决方案
这将返回当前元素的路径。有关此解决方案的更多信息,请参阅我对 XPath 2.0 很好的类似问题的回答。如果您 append //*[@special="yes"]/
,它将返回“特殊”元素的所有路径。
string-join(
(
'',
(
.//ancestor-or-self::*/name(),
concat("@", .//ancestor-or-self::attribute()/name())
)
),
'/'
)
如果您愿意,您可以删除所有换行符,但如果包装得很好,则更容易理解。
弄脏你的手
遗憾的是,PHP 不支持开箱即用的 XPath 2.0,您将不得不在 PHP 中进行循环和连接,但仍然可以使用祖先轴。
在@Rolando Isidoro 解决方案的基础上,这将使他的代码的“主”循环更加优雅和高效(尽管改进很小,可能只在具有非常深结构的非常大的文档中才能注意到):
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++;
}