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

发布于 2024-08-20 00:07:15 字数 56 浏览 3 评论 0原文

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

这可能吗?

I am try to find if a certain node has siblings, and if it does, I would like to know what those siblings are.

Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

音盲 2024-08-27 00:07:15

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

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

这就是您所要做的。

In order to select a node's siblings, you have to use the corresponding XPath axe. Here is how to select all a node's siblings (ignoring the node itself)

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

That's all you have to do.

小姐丶请自重 2024-08-27 00:07:15

我认为使用 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

I think using xpath is your best bet here:

<?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";    
?>

Results in:

title
from
body
送你一个梦 2024-08-27 00:07:15
$xml = new SimpleXMLElement($xmlstr);
$xmlNode = $xml->xpath('root/yourNodeName');
$nodeCount = count($xmlNode); 

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

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

Not sure if this is still useful to you

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文