2010-02-01 121 views

回答

8

有用的,以便選擇一個節點的兄弟姐妹,你必須使用相應的XPath斧頭。這裏是如何選擇所有節點的兄弟姐妹(忽略節點本身)

$siblings = $node->xpath('preceding-sibling::* | following-sibling::*'); 

這就是你所要做的。

1

我認爲使用XPath是你最好的選擇在這裏:

<?php 
$string = <<<XML 
<?xml version='1.0'?> 
<document> 
<title>Forty What?</title> 
<from>Joe</from> 
<to>Jane</to> 
<body> 
    I know that's the answer -- but what's the question? 
</body> 
</document> 
XML; 

function get_all_siblings(SimpleXMLElement $node) 
{ 
    return $node->xpath('preceding-sibling::* | following-sibling::*'); 
} 

$xml = simplexml_load_string($string); 

foreach (get_all_siblings($xml->to) as $e) 
    echo $e->getName()."\n";  
?> 

結果:

title 
from 
body 
+1

由於SimpleXML的工作方式,您不能使用'($ node!= $ e)'過濾上下文節點,因爲即使兩個變量都代表相同的節點,該比較始終爲真。 – 2010-02-01 07:12:08

+0

我不使用SimpleXML已經意識到......我用不同的xpath語法更新了我的代碼(我發現你已經發布了),這使得函數基本上不相關。 – Matthew 2010-02-01 07:48:42

0
$xml = new SimpleXMLElement($xmlstr); 
$xmlNode = $xml->xpath('root/yourNodeName'); 
$nodeCount = count($xmlNode); 

不知道這仍然是你