在PHP中删除XML节点

时间:2013-04-23 10:17:28

标签: php xml

    $xmldoc = new DOMDocument();
    $xmldoc->load('card.xml');
    $root   = $xmldoc->documentElement;
    $fnode  = $root->firstChild;
    // we retrieve the chapter and remove it from the book
    $items = $xmldoc->getElementsByTagName('card');
    foreach ($items as $item){
        $node = $item->getElementsByTagName('cardnumber')->item(0);
        if ($node->nodeValue == $this->cardnumber){
            $node->parentNode->removeChild($node);
            $xmldoc->saveXML();
        }
    }

以上是我用来删除卡片节点的代码,如果卡号匹配,下面是我的XML格式。但如果未能取出卡。有人可以帮忙吗?

<root>
  <card>
    <cardnumber>12345</cardnumber>
    <name>Tan</name>
  </card>
  ....
</root>

3 个答案:

答案 0 :(得分:3)

使用<card> id=2删除simplexml {/ 1}}。

$xml = simplexml_load_string($x); // assume XML in $x
$i = count($xml) - 1; 

for ($i; $i >= 0; $i--) {   
    $card = $xml->card[$i];
    if ($card['id'] == "2") unset($xml->card[$i]);
}

看到它有效:http://codepad.viper-7.com/9cX1qR

答案 1 :(得分:0)

删除节点的方式是正确的。但是你可以在saveXml()之后将它保存在xml中,或者只需打印新的xml并检查你所做的更新。而且根据你的逻辑,保存应该在循环之后完成。 (即)如下,

$xmldoc = new DOMDocument();
$xmldoc->load('card.xml');
$root   = $xmldoc->documentElement;
$fnode  = $root->firstChild;
// we retrieve the chapter and remove it from the book
$items = $xmldoc->getElementsByTagName('card');
foreach ($items as $item){
    $node = $item->getElementsByTagName('cardnumber')->item(0);
    if ($node->nodeValue == $this->cardnumber){
        $node->parentNode->removeChild($node);            
    }
}
$xmldoc->save('newXmlFile.xml');

(OR)

print $xmldoc->saveXML();

答案 2 :(得分:0)

Private Sub UpdatePriceLabel()
    breadPrice = Prices.GetBreadPrice(bread)
    contentsPrice = Prices.GetContentsPrice(contents)
    totalPrice = breadPrice + contentsPrice
    lblPrice.Caption = Format(totalPrice, "$0.00")
End Sub