我正在使用SimpleXML来引入XML提要。我需要获取具有相同名称的第二个节点。
Feed示例是:
<parent-node>
<child-node>
<the-node>
<the-target>Text</target>
</the-node>
<the-node>
<the-target>Text</target>
</the-node>
</child-node>
</parent-node>
由于我所针对的节点使用连字符,我需要使用括号语法
$item->{'parent-node'}->{'child-node'}->{'the-node'}
这将抓住第一个<the-node>
当使用括号语法时,我无法使用以下任何一个选择第二个<the-node>
的<the-target>
...
$item->{'parent-node'}->{'child-node'}->{'the-node[2]'}->{'the-target'}
$item->{'parent-node'}->{'child-node'}->{'the-node'[2]}->{'the-target'}
$item->{'parent-node'}->{'child-node'}->{'the-node'}[2]->{'the-target'}
我的问题是,如何在使用括号语法获取第二个<the-node>
的<target>
时定位childIndex?
- - 更新 - -
在一些答案之后,我尝试了以下但没有运气
$item->{'parent-node'}->{'child-node'}->{'the-node'}[1]->{'the-target'}
$item->{'parent-node'}->{'child-node'}->{'the-node'}->{'the-target'}[1]
$item->{'child-node'}->{'the-node'}->{'the-target'}[1]
SimpleXMLElement存储兄弟节点,就好像它们是一个数组一样。这通常表示值以0为基础的索引存储,即。数组中的第一个值从索引0
开始。
因此,在这种情况下,只能使用索引1
而不是2
访问第二个兄弟节点。
默认情况下也不必遍历根级节点(除非您省略了其他一些XML或使用了一些非默认设置)。
试试这个:
// Will grab the 2nd <the-node/>
$node = $item->{'child-node'}->{'the-node'}[1];
根据您的初始代码是否在没有数组访问权限的情况下工作,您也可以尝试:
// Testing locally I was not able to use this and got an error
// But maybe things are omitted in your question.
$node = $item->{'parent-node'}->{'child-node'}->{'the-node'}[1];
正确的语法如下所示:
$item->{'child-node'}->{'the-node'}[0]; // First the-node
$item->{'child-node'}->{'the-node'}[1]; // Second the-node
如果parent-node
是所有其他元素的根元素,则无法显式访问它。
$item->{'parent-node'}->{'child-node'}->{'the-node'}[0];
上面的代码将导致错误说“试图获取非对象的属性”。
由于parent-node
是顶级根元素,因此无法显式访问它。
只有top根元素的immediate子元素才可以在SimpleXMLElement对象中访问。