0

I'm trying to figure out how to delete a bunch of nodes if they are empty. I have tried this but with no luck:

    $xml = new DOMDocument();
    $xml->preserveWhiteSpace = false;
    $xml->formatOutput = true;
    $xml->loadXML('<library>
      <invites>
        <invite>
          <username>0</username>
          <userid>0</userid>
        </invite>
      </invites>
      <invites/>
      <invites/>
      <invites/>
      <invites/>
      <invites/>
      <invites/>
    </library>');

    echo "<xmp>OLD \n". $xml->saveXML() ."</xmp>";

    $opNodes = $xml->getElementsByTagName('invites');
    foreach($opNodes as $node) {
        $innerHtml = trim($node->nodeValue);
        if(empty($innerHtml)){
            $node->parentNode->removeChild($node);
        }
    }

    echo "<xmp>NEW \n". $xml->saveXML() ."</xmp>";

This only removes some of the , Why?... Please help and thanks in advance :-)

4

1 回答 1

0

看起来修改 DOM 会影响 DOMNodeList ( $opNodes) 的内容并在迭代时导致一些问题。要解决此问题,请将要删除的节点保存在单独的列表中,然后一次将它们全部删除:

$opNodes = $xml->getElementsByTagName('invites');
$remove = array();

foreach ($opNodes as $node) {
    if (!$node->hasChildNodes()) {
        $remove[] = $node;
    }
}

foreach ($remove as $node) {
    $node->parentNode->removeChild($node);
}
于 2012-09-19T17:03:55.577 回答