使用 PHP 的 SimpleXML 访问元素的父元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2174263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access an element's parent with PHP's SimpleXML?
提问by thisismyname
I'm iterating through a set of SimpleXML objects, and I can't figure out how to access each object's parent node. Here's what I want:
我正在遍历一组 SimpleXML 对象,但不知道如何访问每个对象的父节点。这是我想要的:
$divs = simplexml->xpath("//div");
foreach ($divs as $div)
{
$parent_div = $div->get_parent_node(); // Sadly, there's no such function.
}
Seems like there must be a fairly easy way to do this.
似乎必须有一种相当简单的方法来做到这一点。
回答by nickf
You could run a simple XPath query to get it:
您可以运行一个简单的 XPath 查询来获取它:
$parent_div = $div->xpath("parent::*");
And as this is Simplexml and it only has element and attribute nodes and a parent node can only be an element and never an attribute, the abbreviated syntax can be used:
由于这是 Simplexml 并且它只有元素和属性节点,而父节点只能是元素而不能是属性,因此可以使用缩写语法:
$parent_div = $div->xpath("..");
(via: Common Xpath Cheats - SimpleXML Type Cheatsheet (Feb 2013; by hakre))
(来自:Common Xpath Cheats - SimpleXML Type Cheatsheet(2013 年 2 月;by hakre))
回答by Josh Davis
$div->get_parent_node(); // Sadly, there's no such function.
$div->get_parent_node(); // Sadly, there's no such function.
Note that you can extend SimpleXML to make it so. For example:
请注意,您可以扩展 SimpleXML 使其如此。例如:
class my_xml extends SimpleXMLElement
{
public function get_parent_node()
{
return current($this->xpath('parent::*'));
}
}
And now all you have to do is modify the code you use to create your SimpleXMLElement in the first place:
现在您要做的就是首先修改用于创建 SimpleXMLElement 的代码:
$foo = new SimpleXMLElement('<foo/>');
// becomes
$foo = new my_xml('<foo/>');
$foo = simplexml_load_string('<foo/>');
// becomes
$foo = simplexml_load_string('<foo/>', 'my_xml');
$foo = simplexml_load_file('foo.xml');
// becomes
$foo = simplexml_load_file('foo.xml', 'my_xml');
The best part is that SimpleXML will automatically and transparently return my_xmlobjects for this document, so you don't have to change anything else, which makes your get_parent_node()method chainable:
最好的部分是 SimpleXML 将自动且透明地返回my_xml此文档的对象,因此您无需更改任何其他内容,这使您的get_parent_node()方法可链接:
// returns $grandchild's parent's parent
$grandchild->get_parent_node()->get_parent_node();
回答by Rob Wilkerson
If memory serves, an xpath()call returns one or more SimpleXMLElements. If that's the case, then you may be able to use something like:
如果没有记错,xpath()调用会返回一个或多个SimpleXMLElements。如果是这种情况,那么您可以使用以下内容:
$div->xpath( '..' );
# or
$div->xpath( 'parent::*' );

