Delete all elements of a certain type from an XML doc using PHP

泄露秘密 提交于 2019-11-27 08:15:57

问题


I have what should be an easy task: delete <places> nodes and their descendants from an XML document, leaving other nodes.

I tried this code, but it did not work ...

$document->preserveWhiteSpace = false; 
$books = $xpath->query('piletilve_info/places');
//echo "4";

foreach ($books as $places) {
    while($places->hasChildNodes()) {
        $places->removeChild($places->childNodes->item(0));
    }

    $places->parentNode->removeChild($places);
}

Source XML to be processed:

<piletilve_info>
   <places>
      <place>
        ...
      </place>
   </places>
   <other node>
      ...
   </other node>
</piletilve_info>

In the actual data there are more nodes that aren't places, but for simplicity this example shows only a few.

I saw C# examples, but I do not manage to port code to PHP.

Clarification : in code snippet, the variable $books is just a holder for the queried list. The name has no meaning.


回答1:


Goal is to delete whole node leaving other nodes ( in actual there are more, but for simplicity this example shows all

$dom = new DOMDocument;
$dom->load('places.xml');
foreach ($dom->getElementsByTagName('places') as $places)
{
    $places->parentNode->removeChild($places);
}
echo $dom->saveXml();

will remove all <places> elements anywhere in the document, including any children.

Output:

<?xml version="1.0"?>
<piletilve_info>

   <other>
      ...
   </other>
</piletilve_info>



回答2:


When I was using the accepted answer it wouldn't remove all occurrences of the tag. The foreach loop would skip over tags probably because foreach relies on the internal array pointer and changing it within the loop leads to unexpected behavior.

A working solution that I've found looks like this.

$dom = new DOMDocument;
$dom->load('places.xml');
$placesNodes = $dom->getElementsByTagName('places') 
while ($placesNodes->length > 0) {
    $node = $placesNodes->item(0);
    $node->parentNode->removeChild($node);
}
echo $dom->saveXml();


来源:https://stackoverflow.com/questions/4177376/delete-all-elements-of-a-certain-type-from-an-xml-doc-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!