英文:
PHP Simple XML Xpath Move Up Tree (Parent with Name)
问题
我正在使用Xpath与SimpleXML查找子元素,如下所示:
$child=$file->xpath('//w:child')[0];
如果我想选择父元素,可以这样做:
$parent=$child->xpath('..')[0];
但是如果我想要查找名为"any_parent"的父元素或祖父元素,在树的任何级别上,该怎么办?例如:
$any_parent=$child->xpath('any_parent//..')[0];
这种操作是否可行?我希望它相对于$child
,然后向上移动树并选择标签any_parent
。有没有办法做到这一点?
英文:
I am using Xpath with SimpleXML to find child elements like so:
$child=$file->xpath('//w:child')[0];
If I want to select the parent, I can do:
$parent=$child->xpath('..')[0];
But what if I want to find a parent or grandparent called "any_parent", at any level of the tree. For example:
$any_parent=$child->xpath('any_parent//..')[0];
is this possible? I want it to be relative to $child
. And then move up the tree and select the tag any_parent
. Is there a way to do this?
答案1
得分: 2
是的,这是“ancestor”轴。
您正在寻找名为“any_parent”的元素节点:
ancestor::any_parent
^ 这是轴的名称(ancestor,查看全部),两个冒号("::")和节点测试,在这里是元素名称。
PHP/SimpleXMLElement:
$any_parent = $child->xpath('ancestor::any_parent')[0];
**注意:**因为可能没有或多个匹配,直接访问[0]
可能会导致意外结果。
您可以提供一个默认的null
,以表示未找到任何节点,并使用位置测试表示您特别想要第一个节点:
$any_parent = $child->xpath('ancestor::grandparent[1]')[0] ?? null;
或者:
[$any_parent] = $child->xpath('ancestor::grandparent[1]') + [null];
英文:
Yes, this is the ancestor
axis.
You are looking for the element node named any_parent
:
ancestor::any_parent
^ that is the name of the axis (ancestor, see all), two colons ("::") and the node test, which is here the element name.
PHP/SimpleXMLElement:
$any_parent = $child->xpath('ancestor::any_parent')[0];
Note: As there can be none or multiple, directly accessing [0]
may give you unexpected results.
You can provide a default null
for example to express not finding any node and the position test to express you want the first node specifically:
$any_parent = $child->xpath('ancestor::grandparent[1]')[0] ?? null;
or:
[$any_parent] = $child->xpath('ancestor::grandparent[1]') + [null];
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论