4

我想做的是计算根元素下的元素。然后检查同一级别的一个 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>
4

3 回答 3

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');
于 2013-05-19T14:04:47.610 回答
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")));

互动演示

另外,我建议您不要使用0(零)作为 ID 值。

于 2013-05-19T14:11:27.227 回答
1

使用 simplexml,试试这个

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

return $id;
于 2013-05-19T14:14:38.227 回答