php – XML计数元素,如果id存在增加1

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – XML计数元素,如果id存在增加1脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要做的是计算根元素下的元素.然后检查同一级别上的一个id是否具有id值.发生这种情况时,需要增加1.

代码

public function _generate_id()
{
    $id = 0;
    $xpath = new DOMXPath($this->_dom);
    do{
        $id++;
    } while($xpath->query("/*/*[@id=$id]"));

    return $id;
}

例如XMl

<?xML version="1.0"?>
<cataLOG>
    <Book id="0">
        <author>Gambardella,Matthew</author>
        <tITle>XML DeveloPEr's Guide</title>
        <genre>Computer</genre>
        <PRice>44.95</price>
        <publish_date>2000-10-01</publish_date>
        <description>An in-depth look at creating applications
            with XML.</description>
    </book>
    <book id="1">
        <author>Ralls,Kim</author>
        <title>;midnight Rain</title>
        <genre>fantasy</genre>
        <price>5.95</price>
        <publish_date>2000-12-16</publish_date>
        <description>A former Architect baTTLes corporate zombies,an evil sorceress,and her own childhood to become queen
            of the world.</description>
    </book>
</catalog>

解决方法

您可以使用以下xpath查询获取id属性的最大值:

$result = $xpath->query('/*/*[not(../*/@id > @id)]/@id');

在您的函数中,您可以返回此值增加1:

return intval($result->item(0)->nodeValue) + 1;

更新:您也可以使用XPath执行增量操作.注DOMXPath::evaluate()

return $xpath->evaluate('/*/*[not(../*/@id > @id)]/@id + 1');
                                                        |------- +1 in xpath

这将给你2 – 但作为一个双.我建议在返回结果之前转换为整数:

return (integer) $xpath->evaluate('/*/*[not(../*/@id > @id)]/@id + 1');

脚本宝典总结

以上是脚本宝典为你收集整理的php – XML计数元素,如果id存在增加1全部内容,希望文章能够帮你解决php – XML计数元素,如果id存在增加1所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。