使用xml dom从xml文件中删除

时间:2010-12-22 17:13:38

标签: php xml

如何删除颜色为蓝色的xml块(car)?

<?xml version="1.0"?>
<cars>
    <car>
        <color>blue</color>
        <name>jonas</name>
    </car>
    <car>
        <color>green</color>
        <name>123</name>
    </car>
    <car>
        <color>red</color>
        <name>1234</name>
    </car>
</cars>

2 个答案:

答案 0 :(得分:3)

假设您的XML包含在变量$xml中,您可以使用类似下面的代码:

$dom = new DOMDocument; // use PHP's DOMDocument class for parsing XML

$dom->loadXML($xml); // load the XML

$cars = $dom->getElementsByTagName('cars')->item(0); // store the <cars/> element

$colors = $dom->getElementsByTagName('color'); // get all the <color/> elements

foreach ($colors as $item) // loop through the color elements
    if ($item->nodeValue == 'blue') { // if the element's text value is "blue"
        $cars->removeChild($item->parentNode); // remove the <color/> element's parent element, i.e. the <car/> element, from the <cars/> element
    }
}

echo $dom->saveXML(); // echo the processed XML

答案 1 :(得分:1)

如果你有一个很长的xml文件,循环遍历所有<car>项可能需要一段时间。作为@lonesomeday帖子的替代方案,这将使用XPath定位所需的元素:

$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadXML($xml);
libxml_use_internal_errors(false);

$domx = new DOMXPath($domd);
$items = $domx->query("//car[child::color='blue']");

$cars = $domd->getElementsByTagName("cars")->item(0);
foreach($items as $item) {
  $cars->removeChild($item);
}