2010-12-22 130 views
2

如何删除xml块(汽车)哪里的颜色是蓝色的?从xml文件中删除xml dom

<?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> 

回答

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

如果你有很长的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); 
} 
+0

+1好听点 - 你需要的基准制定出什么是最好根据`car`元素的量。 – lonesomeday 2010-12-22 17:33:42