需要有关使用 PHP 删除 XML 中的子项的帮助


need help on removing child in xml using php

我正在尝试使用 php 脚本从我的作业.xml文件中删除孩子。

我的工作.xml看起来像:

    <jobs>
    <event jobid="1">
    <title>jobtitle</title>
    <desc>description</desc>
    <date>postdate</date>
    </event>
    <event jobid="2">
    <title>jobtitle</title>
    <desc>description</desc>
    <date>postdate</date>
    </event>
    <event jobid="3">
    <title>jobtitle</title>
    <desc>description</desc>
    <date>postdate</date>
    </event>
    </jobs>

我创建了一个 php 脚本,在其中我从用户那里获取 jobid,并在提交和删除具有该 jobid 的事件子项时。

但问题是,当我创建一个新作业时,我得到一个重复的 jobid,因为当我创建新作业事件时,我使用 $jobid = $xmlobj->count() + 1;

有人可以帮助我吗?我更喜欢使用php脚本,但java脚本也可以。

编辑:

这是我要删除的代码:

    <?php
    $jobs = simplexml_load_file('jobs.xml');
    $jobid = $_POST['jobid'];
    foreach ($jobs->children() as $event) {
    if($event->attributes()->jobid == $jobid)
    {
        $dom=dom_import_simplexml($event);
    $dom->parentNode->removeChild($dom);
    }
    }
    $jobs->asXML('jobs.xml');
    ?>

请注意:这仅适用于新创建的文件。现有文件将需要在根元素<jobs>上手动添加next_jobid="N"

欢迎使用进一步的改进:

class JobsXML
{
    public function __construct($filename)
    {
        $this->filename = $filename;
        $this->dom = new DOMDocument;
        $this->dom->formatOutput = true;
        @$this->dom->load($filename);
        $this->xpath = new DOMXPath($this->dom);
        if ($this->xpath->query('//jobs')->length == 0) {
            $this->root = $this->dom->createElement('jobs');
            $this->root->setAttribute('next_jobid', 1);
            $this->dom->appendChild($this->root);
        } else {
            $this->root = $this->xpath->query('//jobs')->item(0);
        }
    }
    public function insertEvent($title, $desc, $date)
    {
        $next_jobid = $this->root->getAttribute('next_jobid');
        $event = $this->dom->createElement('event');
        $event->setAttribute('jobid', $next_jobid);
        $event->appendChild($this->dom->createElement('title', $title));
        $event->appendChild($this->dom->createElement('desc', $desc));
        $event->appendChild($this->dom->createElement('date', $date));
        $this->root->appendChild($event);
        $this->root->setAttribute('next_jobid', intval($next_jobid) + 1);
    }
    public function removeEvent($jobid)
    {
        foreach ($this->xpath->query("//event[@jobid=$jobid]") as $node) {
            $node->parentNode->removeChild($node);
        }
    }
    public function save()
    {
        $this->dom->save($this->filename);
    }
}

插入事件:

$jobs = new JobsXML('jobs.xml');
$jobs->insertEvent('jobtitle', 'description', 'postdate');
$jobs->save();

删除事件:

$jobs = new JobsXML('jobs.xml');
$jobs->removeEvent(1);
$jobs->save();
$jobs = simplexml_load_file('jobs.xml');
$jobid = 1;
foreach ($jobs->children() as $event) {
    if($event->attributes()->jobid == $jobid){
        $dom=dom_import_simplexml($event);
        $dom->parentNode->removeChild($dom);
    }
}
echo $jobs->asXML();