查找节点是否具有使用simplexml的兄弟节点

时间:2010-02-01 06:00:55

标签: php xml simplexml siblings

我试图找出某个节点是否有兄弟姐妹,如果有,我想知道这些兄弟姐妹是什么。

这可能吗?

3 个答案:

答案 0 :(得分:8)

为了选择节点的兄弟节点,您必须使用相应的XPath ax。以下是如何选择节点的所有兄弟节点(忽略节点本身)

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

这就是你所要做的一切。

答案 1 :(得分: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

答案 2 :(得分:0)

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

不确定这对您是否仍然有用