我使用SimpleXML来输入XML。我需要获取同名的第二个节点。
提要示例是:
<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>时,如何将目标定位到<target>?
--更新--
在回答了一些问题之后,我尝试了以下几个没有运气的方法
$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]
发布于 2016-11-28 19:17:27
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];发布于 2016-11-28 19:32:51
正确的语法如下所示:
$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是顶级根元素,所以不能显式地访问它。
只有顶部根元素的直接子元素才能在SimpleXMLElement对象中访问。
https://stackoverflow.com/questions/40851643
复制相似问题