douwuying4709 2018-01-28 07:15
浏览 28
已采纳

取消设置xml子项不起作用

I have the xml file "flashcards.xml":

<flashcards>
 <category name="testCategory">
    <card front="A" back="B"/>
    <card front="C" back="D"/>
    <card front="E" back="F"/>
 </category>
</flashcards>

I try to remove a category by given attribute "name" like this in 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());
  }
?>

This code should load the file, looks for the category child with the attribute "remCat" and unsets it. If I print out $toRemove its the right node, but var_dump($xml->asxml()); prints the unchanged file. The child is not removed.

  • 写回答

1条回答 默认 最新

  • dongzai3917 2018-01-28 07:38
    关注

    Using unset in this case is difficult as your trying to use $xml->$toRemove. So your trying to use the SimpleXMLElement returned by XPath to remove the element in the original document. This would work if you wanted to unset($xml->category[0]); but not with a SimpleXMLElement.

    You can instead use...

    $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);
    

    This uses the much more powerful DOM api.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部