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

时间:2013-05-19 13:48:37

标签: php xml

我要做的是计算根元素下的元素。然后检查同一级别上的一个id是否具有id值。发生这种情况时,需要增加一个。

代码

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>

3 个答案:

答案 0 :(得分:2)

您可以使用以下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');

答案 1 :(得分:1)

我建议您首先创建一个包含所有现有ID值的数组(这是一个单一的xpath查询),然后检查它:

$id = 0;
while(isset($ids[$id])) {
    $id++;
}

echo $id; # 2

创建这样的列表在SimpleXML上运行xpath是微不足道的,但是这可以很容易地移植到DOMXPath以及iterator_to_array

<?php
$buffer = <<<BUFFER
<?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>
BUFFER;

$xml = simplexml_load_string($buffer);
$ids = array_flip(array_map('intval', $xml->xpath("/*/*/@id")));

Interactive Demo

此外,我建议您不要将0(零)用作ID值。

答案 2 :(得分:1)

使用simplexml,试试这个

$xml = simplexml_load_string($this->_dom);
$id = is_array($xml->book) ? $xml->book[count($xml->book)-1]->attributes()->id : 0;

return $id;