0

我试图<wcccanumber>从我的 xml 中删除父节点,如果它的内容符合某个标准,但它只会删除一个节点<wcccanumber>。如何删除整个父节点?

这是我的代码:

$xml = new SimpleXMLElement('<xml/>');

if (file_exists("xml/units/E01.xml")) {

    $xml = simplexml_load_file("xml/units/E01.xml");

    echo "File exists";
    echo "</br>";

    $wcccanumber = "121202482";

    foreach ($xml->call->wcccanumber as $call) {
        if ($call == $wcccanumber) {
            $dom = dom_import_simplexml($call);
            $dom->parentNode->removeChild($dom);

            $fp = fopen("xml/units/E01.xml","wb");
            fwrite($fp,$xml->asXML());
            fclose($fp);
        }
    }
}

这是xml:

<xml>
  <call>
     <wcccanumber>121202482</wcccanumber>
     <currentcall>FALL</currentcall>
     <county>W</county>
     <id>82</id>
     <location>234 E MAIN ST</location>
     <callcreated>12:26:09</callcreated>
     <station>HBM</station>
     <units>E01</units>
     <calltype>M</calltype>
     <lat>45.5225067888299</lat>
     <lng>-122.987112718574</lng>
     <inputtime>12/18/2012 12:27:01 pm</inputtime>
  </call>
</xml>
4

1 回答 1

1

遍历并与call比较。转换为 dom 并将其删除 ( )。$call->wcccanumber$wcccanumber$callparentNode->removeChild

foreach ($xml->call as $call) {
    if ($call->wcccanumber == $wcccanumber) {
        $dom = dom_import_simplexml($call);
        $dom->parentNode->removeChild($dom);
        $fp = fopen("xml/units/E01.xml","wb");
        fwrite($fp,$xml->asXML());
        fclose($fp);
    }
}

如果有多个删除,则在所有删除完成只保存一次是有意义的。

$deletionCount = 0;

foreach ($xml->call as $call) {
    if ($call->wcccanumber != $wcccanumber) {
        continue;
    }
    $dom = dom_import_simplexml($call);
    $dom->parentNode->removeChild($dom);
    $deletionCount++;
}

if ($deletionCount) {
    file_put_contents("xml/units/E01.xml", $xml->asXML());
}
于 2012-12-18T21:48:03.223 回答