删除XML节点如果为空?

时间:2012-09-19 16:15:07

标签: php xml

我试图弄清楚如果它们是空的,删除一堆节点。我试过这个但没有运气:

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

这只删除了一些,为什么?...请提前帮助和感谢: - )

1 个答案:

答案 0 :(得分: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);
}