如果Child为空,请删除节点?

时间:2012-09-18 08:50:23

标签: php xml

如果特定的孩子是空的,我希望能够删除节点树,但似乎做错了什么?

这是我得到的:

$xml = new DOMDocument();
$xml->loadXML('<?xml version="1.0" encoding="ISO-8859-1"?>
<data>
  <game id="1">
    <opponent>Michael</opponent>
    <oppid>1</oppid>
  </game>
  <game id="2">
    <opponent>Trish</opponent>
    <oppid>55</oppid>
  </game>
  <game id="3">
    <opponent/>
    <oppid>24</oppid>
  </game>
  <game id="4">
    <opponent>Betty</opponent>
    <oppid>12</oppid>
  </game>
</data>

');

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

$xpath = new DOMXpath($xml);
foreach($xpath->query('//game') as $node) {
    if($node->opponent == ''){
        echo 'Test<br>';
        $node->parentNode->removeChild($node);
    }

}

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

我打印出4“测试”并且在新的xmp中我什么都没得到?我做错了什么?

请提前帮助和谢谢。

2 个答案:

答案 0 :(得分:0)

将您的if条件更改为以下内容:

if($node->opponent->nodeValue == '')

答案 1 :(得分:0)

<?php
$xml = new DOMDocument();
$xml->loadXML('<?xml version="1.0" encoding="ISO-8859-1"?>
<data>
<game id="1">
    <opponent>Michael</opponent>
    <oppid>1</oppid>
</game>
<game id="2">
    <opponent>Trish</opponent>
    <oppid>55</oppid>
</game>
<game id="3">
    <opponent/>
    <oppid>24</oppid>
</game>
<game id="4">
    <opponent>Betty</opponent>
    <oppid>12</oppid>
</game>
</data>

');

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

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

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

我想知道它为什么不起作用......现在它有效。