我想要做的是计算根元素下的元素.然后检查同一级别上的一个id是否具有id值.发生这种情况时,需要增加1.
代码
public function _generate_id()
{
$id = 0;
$xpath = new DOMXPath($this->_dom);
do{
$id++;
} while($xpath->query("/*/*[@id=$id]"));
return $id;
}
例如xml
Gambardella, Matthew
XML Developer's GuideComputer
44.95
2000-10-01
An in-depth look at creating applications
with XML.
Ralls, Kim
Midnight RainFantasy
5.95
2000-12-16
A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.
解决方法:
您可以使用以下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
来源: https://codeday.me/bug/20190625/1284269.html