<?xml version="1.0" encoding="utf-8" ?><bookstore><book category="COOKING"><title lang="en">Everyday Italian</title><author>Giada De Laurentiis</author><year>2018</year><price>29.00</price></book><book category="CHILDREN"><title lang="en">Harry Potter</title><author>J K. Rowling</author><year>2020</year><price>37.54</price></book><book category="WEB"><title lang="en">Learning XML</title><author>Erik T. Ray</author><year>2021</year><price>18.74</price></book></bookstore>
删除第三本书的year元素节点
<?php$dom = new DOMDocument('1.0','utf-8');$dom->load("bookstore.xml");//找到year元素节点$year = $dom->getElementsByTagName('year')->item(2);$year->parentNode->removeChild($year);//保存$dom->save('delete_bookstore.xml');?>
删除所有书本的year元素节点。
<?php$dom = new DOMDocument('1.0','utf-8');$dom->load("bookstore.xml");//找到所有的year元素节点$years = $dom->getElementsByTagName('year');///这么删除是有问题的foreach ($years as $year){$year->parentNode->removeChild($year);}///第一步, 先保存$temp = array();foreach ($years as $year){$temp[] = $year;}//第二步, 再删除foreach ($temp as $v){$v->parentNode->removeChild($v);}//保存$dom->save('delete2_bookstore.xml');?>
把稳:牢记, 不要在删除的时候, 再去遍历这个节点, 节点的构造已经发生了变革, 导致遍历的时候会涌现差错。
办理办法, 便是将这两个操作分开处理。先得打所有的这些节点, 将其保存到一个临时变量中, 然后再进行删除。