查找节点是否具有使用simplexml的兄弟节点
答
有用的,以便选择一个节点的兄弟姐妹,你必须使用相应的XPath斧头。这里是如何选择所有节点的兄弟姐妹(忽略节点本身)
$siblings = $node->xpath('preceding-sibling::* | following-sibling::*');
这就是你所要做的。
答
我认为使用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
答
$xml = new SimpleXMLElement($xmlstr);
$xmlNode = $xml->xpath('root/yourNodeName');
$nodeCount = count($xmlNode);
不知道这仍然是你
由于SimpleXML的工作方式,您不能使用'($ node!= $ e)'过滤上下文节点,因为即使两个变量都代表相同的节点,该比较始终为真。 – 2010-02-01 07:12:08
我不使用SimpleXML已经意识到......我用不同的xpath语法更新了我的代码(我发现你已经发布了),这使得函数基本上不相关。 – Matthew 2010-02-01 07:48:42