remove element from xml

后端 未结 2 1891
醉话见心
醉话见心 2020-12-20 06:58

in my xml file i want to remove record element according to title My xml file is



  
    <         


        
相关标签:
2条回答
  • 2020-12-20 07:13

    From the question I understood you want to remove the <record> elements with a <title> child that contains a specific text. The solution is more verbose than it needs to be and $attrValue is suggesting the DOMText of the title element is an Attribute, which it isnt. But anyway, let's remove all this and use XPath:

    $searchString = 'Title:4';
    
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    $doc->load('playlist.xml');
    
    $xPath = new DOMXPath($doc);
    $query = sprintf('//record[./title[contains(., "%s")]]', $searchString);
    foreach($xPath->query($query) as $node) {
        $node->parentNode->removeChild($node);
    }
    $doc->formatOutput = TRUE;
    echo $doc->saveXML();
    

    The XPath says, find all record nodes, which have a child title with a text node containing the search string. Note that containing, does not mean is equal to, so if you would use "Title:" as $searchString, it would remove all movies but "The_Princess_And_The_Frog_HD". If you want to remove exact titles, change the XPath to

    '//record[./title[text()="%s"]]'
    

    Learn more about XPath at W3C but note that PHP supports XPath1.0 only.

    0 讨论(0)
  • 2020-12-20 07:26

    You can only call removeChild() on the respective parent node. Since the $nodeToRemove is not a direct child of $thedocument (it is a descendant), you get the "not found" error.

    if ($nodeToRemove != null) {
      $nodeToRemove->parentNode->removeChild($nodeToRemove);
    }
    
    0 讨论(0)
提交回复
热议问题