取消设置 xml child 无效
Unset xml child not working
我有 xml 文件 "flashcards.xml":
<flashcards>
<category name="testCategory">
<card front="A" back="B"/>
<card front="C" back="D"/>
<card front="E" back="F"/>
</category>
</flashcards>
我尝试通过给定属性 "name" 删除类别,就像 php 中这样:
<?php
$xml = simplexml_load_file("flashcards.xml");
if (isset($_POST['remCat'])) {
$remCat = $_POST['remCat'];
$path = 'category[@name="' . $remCat . "\"]";
$allCategories = $xml->xpath($path);
$toRemove = $allCategories[0];
unset($xml->$toRemove);
var_dump($xml->asxml());
}
?>
此代码应加载文件,查找具有属性 "remCat" 的类别 child 并将其取消设置。如果我打印出 $toRemove
它是正确的节点,但是 var_dump($xml->asxml());
打印出未更改的文件。 child 未删除。
在这种情况下使用 unset
很困难,因为您尝试使用 $xml->$toRemove
。因此,您尝试使用 XPath 返回的 SimpleXMLElement 来删除原始文档中的元素。如果您想要 unset($xml->category[0]);
但不使用 SimpleXMLElement,这会起作用。
您可以改为使用...
$allCategories = $xml->xpath($path);
echo $allCategories[0]->asXML().PHP_EOL;
$toRemove = $allCategories[0];
//unset($xml->$toRemove);
$dom=dom_import_simplexml($toRemove);
$dom->parentNode->removeChild($dom);
这使用了更强大的 DOM api.
我有 xml 文件 "flashcards.xml":
<flashcards>
<category name="testCategory">
<card front="A" back="B"/>
<card front="C" back="D"/>
<card front="E" back="F"/>
</category>
</flashcards>
我尝试通过给定属性 "name" 删除类别,就像 php 中这样:
<?php
$xml = simplexml_load_file("flashcards.xml");
if (isset($_POST['remCat'])) {
$remCat = $_POST['remCat'];
$path = 'category[@name="' . $remCat . "\"]";
$allCategories = $xml->xpath($path);
$toRemove = $allCategories[0];
unset($xml->$toRemove);
var_dump($xml->asxml());
}
?>
此代码应加载文件,查找具有属性 "remCat" 的类别 child 并将其取消设置。如果我打印出 $toRemove
它是正确的节点,但是 var_dump($xml->asxml());
打印出未更改的文件。 child 未删除。
在这种情况下使用 unset
很困难,因为您尝试使用 $xml->$toRemove
。因此,您尝试使用 XPath 返回的 SimpleXMLElement 来删除原始文档中的元素。如果您想要 unset($xml->category[0]);
但不使用 SimpleXMLElement,这会起作用。
您可以改为使用...
$allCategories = $xml->xpath($path);
echo $allCategories[0]->asXML().PHP_EOL;
$toRemove = $allCategories[0];
//unset($xml->$toRemove);
$dom=dom_import_simplexml($toRemove);
$dom->parentNode->removeChild($dom);
这使用了更强大的 DOM api.