如何获取 simpleXML 来创建 ID

发布于 2024-08-18 12:10:39 字数 133 浏览 2 评论 0原文

我有一个 extiing xml 文件,其 id 为 1 - 20,当我创建新的 xml 文件时,我需要它来将 ID 添加到文件中,我该怎么做?

我知道你会如何使用 SQL 来做到这一点,但不知道如何使用 xml

请帮忙

I have an exctiing xml file which has id's 1 - 20 when I create a new xml file I need it to add the ID to the file how can I do this ?

I know how you would do it with SQL but not with xml

please help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝天白云 2024-08-25 12:10:39

如果你的xml已经从最低到最高排序,你可以执行这个xpath查询:

$res = $doc->xpath('/list/a[not(@id <= preceding-sibling::a/@id) and ' .
  'not(@id <= following-sibling::a/@id)]/@id');

$nextId = is_array($res) && count($res) ? (intval($res[0]->id) + 1) : 0;

否则,你可以像这样找到最大id(假设id是一个属性):

$xml = '<list><a id="1" /><a id="2" /><a id="3" /></list>';
$doc = simplexml_load_string($xml);
$max = -1;
foreach ($doc->xpath('/list/a/@id') as $el) {
  $i = intval($el->id); if ($i > $max) $max = $i;
}
echo "Max: $max"; 

上面打印“3”,所以你的新id是4

或使用 Veger 的解决方案 也可以

if your xml is already ordered from lowest to highest, you can do this xpath query:

$res = $doc->xpath('/list/a[not(@id <= preceding-sibling::a/@id) and ' .
  'not(@id <= following-sibling::a/@id)]/@id');

$nextId = is_array($res) && count($res) ? (intval($res[0]->id) + 1) : 0;

otherwise, you can find the max id like so (assuming id is an attribute):

$xml = '<list><a id="1" /><a id="2" /><a id="3" /></list>';
$doc = simplexml_load_string($xml);
$max = -1;
foreach ($doc->xpath('/list/a/@id') as $el) {
  $i = intval($el->id); if ($i > $max) $max = $i;
}
echo "Max: $max"; 

the above prints "3", so your new id is 4

or use Veger's solution which will also work

或十年 2024-08-25 12:10:39

使用一些 XPath 查询和 php 代码查找现有文件中的最高 ID。

$ids = $xml->xpath("element/id"); // or something that fits your XML document
asort($ids);                      // or use some other sorting algorithm
$highest_id = end($ids);

我对 xpath 查询不是很了解,因此我想在查询期间可能有一些技巧对其进行排序,但如果可以优化此示例,其他人可能会指出这一点。

接下来创建新的 XML 文档并向其添加最高 ID。

Find the highest ID in your existing file, using some XPath query and php code.

$ids = $xml->xpath("element/id"); // or something that fits your XML document
asort($ids);                      // or use some other sorting algorithm
$highest_id = end($ids);

I am not very knowledgeable about xpath queries, so there might be some trick to sort it during the query I suppose, but someone else will probably point this out if this example can be optimised.

Next create your new XML document and add the highest ID to it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文