删除多个emty xml记录?

时间:2012-12-28 12:16:21

标签: php xml

我试图找出如果没有属性我如何删除多个xml“记录”?

这是我现在直到尝试的内容:

$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML('<friends>
  <friend id="779">
    <name>ML76</name>
    <games/>
    <wins/>
  </friend>
  <friend id="131">
    <name>Puttepigen67</name>
    <games/>
    <wins/>
  </friend>
  <friend id="17">
    <name>rikkelolk</name>
    <games>3</games>
    <wins>2</wins>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
</friends>');

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

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

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

foreach ($remove as $node) {
    $node->parentNode->removeChild($node);
}

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

我在最后的XML-&gt; saveXML()中没有得到任何东西。

我做错了什么?

提前致谢:-)

1 个答案:

答案 0 :(得分:1)

使用xpath

$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML('<friends>
  <friend id="779">
    <name>ML76</name>
    <games/>
    <wins/>
  </friend>
  <friend id="131">
    <name>Puttepigen67</name>
    <games/>
    <wins/>
  </friend>
  <friend id="17">
    <name>rikkelolk</name>
    <games>3</games>
    <wins>2</wins>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
  <friend id="">
    <name/>
    <games/>
    <wins/>
  </friend>
</friends>');

$xpath = new DOMXPath($xml);

// prepare the xpath query to find the empty nodes
$node = $xpath->query("//friend[@id='']");

// if found, append the new "value" node
if( $node->length ) {
    foreach ($node as $n) {
        $n->parentNode->removeChild( $n );
    }
}
header('content-type: text/xml');
echo $xml->saveXML();

希望它有所帮助。