获取 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

这是可以实现的吗?我一直在尝试获得这个,但我无法找到解决方案。

首先选择带有xpath()<record>,然后将其删除:

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

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

现在使用未设置:

unset($record[0]);

查看更改:

echo $xml->asXML();