0

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

这是我得到的:

$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 中我什么也没得到?我究竟做错了什么?

请提前帮助和感谢。

4

2 回答 2

0

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

if($node->opponent->nodeValue == '')
于 2012-09-18T09:01:45.610 回答
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>";

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

于 2012-09-18T09:13:18.150 回答