我有一个元素的id属性值。
我想只选择其子女(不是所有后代)。
我用过
$childElements = $xml->xpath('//entity[@id=212323]');
print_r($childElements);
但是会选择所有后代并打印出来。我只想选择1代儿童。我怎么能这样做?
<entity id=212323>
<this>asd</this>
<this>asd</this>
<this>asd</this>
<this>
<notThis>asd</notThis>
<notThis>asd</notThis>
<notThis>asd</notThis>
</this>
</entity>
(因为层次结构非常长,因此对所有后代进行处理会降低进程的速度,而且获取不必要的数据并不聪明。)
答案 0 :(得分:4)
你可以用这个:
//entity[@id=212323]/child::*[not(boolean(child::*))]
仅选择没有子节点的节点。如果这还不够好,你也期望像:
<entity id=212323>
<this>asd</this>
<this>asd</this>
<this>asd</this>
<this>
text node 1
<notThis>asd</notThis>
<notThis>asd</notThis>
<notThis>asd</notThis>
text node 2
</this>
</entity>
你应该做更多的研究。在此示例中,text node 1
和text node 2
被视为<this>
元素的子项。您需要找出(我不确定是否可能)如何在xPath表达式中将这两个节点与其他节点(如<notThis>asd</notThis>
)区分开来。