获取XML个节点位置

Get XML node position

我有以下XML

    <cds>
        <record>
            <id>1</id>
            <artist>Rammstein</artist>
            <album>random</album>
            <trackNumbers>11</trackNumbers>
        </record>
        <record>
            <id>2</id>
            <artist>Rammstein</artist>
            <album>random</album>
            <trackNumbers>18</trackNumbers>
        </record>
   </cds>

我想删除我从另一个 php 文件传递​​的标识符 "ID" 的记录。因此,如果我没记错的话,我需要记录节点的位置来删除该节点。

$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");

unset($xml->record[x]); // x should be the id passed

这可以实现吗?我一直在努力获得这个我找不到解决方案。

首先select <record>xpath(),然后删除它:

$xml = simplexml_load_string($x); // assume XML in $x
$record = $xml->xpath("/cds/record[id='2']")[0];

这会将 xpath "query" 的第一个结果(索引 = 0)存储在 $record 中。它将是一个 id = 2 的记录节点。请注意,PHP >= 5.4 需要进行数组取消引用。

现在使用 unset:

unset($record[0]);

查看变化:

echo $xml->asXML();