0

我试图弄清楚如果没有属性,我如何删除多个 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->saveXML() 中没有得到任何东西。

我究竟做错了什么?

提前致谢 :-)

4

1 回答 1

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();

希望能帮助到你。

于 2012-12-28T12:19:59.173 回答