我有一个像这样的XML文件:
<T_Person>
<Person>
<ID_Person>5B32EB71-E527-482B-B01B-07502D968E70</ID_Person>
<First_Name_Person>u</First_Name_Person>
</Person>
<Person>
<ID_Person>C47E80CF-6BDB-49CE-BCF4-20E7E08835BF</ID_Person>
<First_Name_Person>l</First_Name_Person>
</Person>
<Person>
<ID_Person>84E8912E-B8F8-4A94-89D6-21B996C69363</ID_Person>
<First_Name_Person>n</First_Name_Person>
</Person>
<Person>
<ID_Person>3DFBDC33-F03E-4579-9D93-256A0FE1BCDA</ID_Person>
<First_Name_Person>h</First_Name_Person>
</Person>
</T_Person>
如果我想删除所选ID_person
的元素,我该怎么办?
$person = $data->getElementsByTagName('Person')->item(0);
$delete = $data->removeChild($person);
如果我运行它,它将删除顶部元素。如果我想删除随机元素该怎么办?
答案 0 :(得分:0)
按ID删除元素:
$id = '84E8912E-B8F8-4A94-89D6-21B996C69363';
$people = $data->getElementsByTagName('Person');
$toRemove = null;
foreach ($people as $person) {
$personId = $person->getElementsByTagName('ID_Person')->item(0)->nodeValue;
// have to be careful with removeChild in a foreach loop
if ($personId === $id) {
$toRemove = $person;
}
}
if ($toRemove) {
$delete = $data->removeChild($toRemove);
}
这是一个example script。
要删除随机元素,请使用rand
:
$people = $data->getElementsByTagName('Person');
$person = $people->item(rand(1, $people->length) - 1);
$delete = $data->removeChild($person);