从xml中删除元素

时间:2010-07-23 11:54:40

标签: php xml

在我的xml文件中我想根据标题删除记录元素 我的xml文件是

<?xml version="1.0"?>
<gallerylist>
  <record>
    <movie>videos/Avatar_HD.flv</movie>
    <title>Title:</title>
    <desc>Description</desc>
    <preview>videos/previews/avatar.jpg</preview>
    <imgplaylist>videos/imgplaylist/p1.jpg</imgplaylist>
    <category>Category</category>
  </record>
 <record>
    <movie>videos/The_Princess_And_The_Frog_HD.flv</movie>
    <title></title>
    <desc>fdgdd</desc>
    <preview>videos/previews/frog.jpg</preview>
    <imgplaylist>videos/imgplaylist/p4.jpg</imgplaylist>
    <category>Category1</category>
 </record>
    <record>
        <movie>videos/Prince_of_Persia_The_Sands_of_Time_HD.flv</movie>
        <title>Title:2</title>
        <desc>xzcXZ</desc>
        <preview>videos/previews/sandsoftime.jpg</preview>
        <imgplaylist>videos/imgplaylist/p2.jpg</imgplaylist>
        <category>Category2</category>
    </record>
    <record>
        <movie>videos/Sherlock_Holmes_HD.flv</movie>
        <title>Title:4</title>
        <desc>dfgdf</desc>
        <preview>videos/previews/sherlock.jpg</preview>
        <imgplaylist>videos/imgplaylist/p7.jpg</imgplaylist>
        <category>Category4</category>
    </record>
</gallerylist>

我的php文件是

        <?php

          $doc = new DOMDocument; 
           $doc->load('playlist.xml');

            $thedocument = $doc->documentElement;

             $list = $thedocument->getElementsByTagName('title');
           $nodeToRemove = null;
              foreach ($list as $domElement){
                  $attrValue = $domElement->nodeValue;
                 if ($attrValue == 'Title:4') {
                  $nodeToRemove = $domElement; 
                         }
                      }


             if ($nodeToRemove != null)
               $thedocument->removeChild($nodeToRemove);

                  $doc->saveXML(); 
                      ?>

它出现以下错误: -

致命错误:D:\ wamp \ www \ funkeymusic \ admin \ update_video.php中未捕获的异常'DOMException',消息'未找到错误':22堆栈跟踪:#0 D:\ wamp \ www \ funkeymusic \ admin \ update_video.php(22):DOMNode-&gt; removeChild(Object(DOMElement))在第22行的D:\ wamp \ www \ funkeymusic \ admin \ update_video.php中抛出#1 {main}

2 个答案:

答案 0 :(得分:4)

您只能在相应的父节点上调用removeChild()。由于$nodeToRemove不是$thedocument的直接子项(它是后代),因此会出现“未找到”错误。

if ($nodeToRemove != null) {
  $nodeToRemove->parentNode->removeChild($nodeToRemove);
}

答案 1 :(得分:4)