通过选择值删除XML dom doc上的节点

Trying to make an API for currency conversion,

Need to select a specific currency and delete it from the xml file...

XML file looks like this:

<currencies>
    <currency>
        <ccode>CAD</ccode>
        <cname>Canadian Dollar</cname>
        <cntry>Canada</cntry>
    </currency>
    <currency>
        <ccode>CHF</ccode>
        <cname>Swiss Franc</cname>
        <cntry>Liechtenstein, Switzerland</cntry>
    </currency>
    <currency>
        <ccode>CNY</ccode>
        <cname>Yuan Renminbi</cname>
        <cntry>China</cntry>
    </currency>
...etc

I need to use php to select and delete the specific currency, at the moment trying this:

<?php
$dom = new DOMDocument("1.0", "utf-8");
$dom->load('data/ccodes.xml');
$nodes = $dom->getElementsByTagName("currencies");
foreach ($nodes as $n){
    if($n->getAttribute("ccode") == "CAD") {
        $parent = $n->parentNode;
        $parent->removeChild($n);
    }
  }
echo $dom->saveXML();
?>

But It's not working.... I'm pretty sure it's really simple but I have no idea what I'm doing with coding... :/

Need to make it so I can just change CAD to whatever to delete any currency I need to...

1个回答

Your iterating the root node currencies but I think you meant to iterate the currency nodes. ccode is not an attribute node, but a child element node. Even if you iterate currency nodes with the correct condition it would still not fully work.

DOMElement::getElementsByTagName() returns a live result. Inside the loop you modify the DOM and the list is modified as well. You could us a for loop to iterate it backwards, use iterator_to_array() to materialize the node list into an array or use Xpath. DOMXpath::evaluate() returns a node list, but it is not a live result. So the list will not change if you modify the document.

$document = new DOMDocument();
//$document->load('data/ccodes.xml');
$document->loadXml($xml);
$xpath = new DOMXpath($document);

foreach ($xpath->evaluate('/currencies/currency[ccode="CAD"]') as $node) {
  $node->parentNode->removeChild($node);    
}

echo $document->saveXML();

Output:

<?xml version="1.0"?>
<currencies>

    <currency>
        <ccode>CHF</ccode>
        <cname>Swiss Franc</cname>
        <cntry>Liechtenstein, Switzerland</cntry>
    </currency>
    <currency>
        <ccode>CNY</ccode>
        <cname>Yuan Renminbi</cname>
        <cntry>China</cntry>
    </currency>
</currencies>
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐