1

我有一个这样的 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>

如果我想通过 selected 删除元素ID_person,我该怎么办?

$person = $data->getElementsByTagName('Person')->item(0);
$delete = $data->removeChild($person);

如果我运行它,它将删除顶部元素。如果我想删除一个随机元素怎么办?

4

1 回答 1

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);
}

这是一个示例脚本

要删除随机元素,请使用rand

$people = $data->getElementsByTagName('Person');
$person = $people->item(rand(1, $people->length) - 1);
$delete = $data->removeChild($person);

参考:rand() 文档DOMNodeList示例

于 2013-11-07T09:56:20.720 回答