【问题标题】:xpath - check if element occurs more than oncexpath - 检查元素是否多次出现
【发布时间】:2017-09-26 12:29:53
【问题描述】:

我正在尝试使用 xpath 检查一个元素是否多次出现。

XML:

<XML>
    <containers>
        <container id="1">
        </container>
        <container id="2">
        </container>
    </containers>
</XML>

我用下面的简单 xpath 表达式试了一下

$xml->xpath('/XML/containers/container');

我明白了:

Element='<container id="1">
        </container>'
Element='<container id="2">
        </container>'

但结果我想要一个类似数组的东西

$containers = array('container', 'container');

如何存档?

【问题讨论】:

  • 在 XPath 中 - 你可以使用 count(/XML/containers/container),但不幸的是 SimpleXML 不支持这种类型的表达式 (AFAIK)

标签: php xml xpath


【解决方案1】:

您不需要数组来检查匹配的数量。只需count() XPath 的结果,它就会给你你的号码:

$a = '<XML>
<containers>
    <container id="1">
    </container>
    <container id="2">
    </container>
</containers>
</XML>';
$xml = simplexml_load_string($a);
$containers = $xml->xpath('/XML/containers/container');
$totalContainers = count($containers); // 2

Demo

【讨论】:

    猜你喜欢
    • 2020-12-03
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 2022-07-06
    相关资源
    最近更新 更多