从这个xml文件我想根据属性id删除图片节点。 我写了PHP代码,但它不起作用。
<gallery>
<organizate>
<organization w="3" h="1" space="17"/>
<organization w="4" h="2" space="17"/>
<organization w="6" h="3" space="7"/>
</organizate>
<pictures>
<picture target="events/preview/10picture1.jpg" title="test1" movie="" text="test1" link="events_calender.php" id="38"/>
<picture target="events/preview/8picture7.jpg" title="test2" movie="" text="cxvxc" link="events_calender.php" id="39"/>
<picture target="events/preview/5picture10.jpg" title="test3" movie="" text="test3" link="events_calender.php" id="40"/>
</pictures>
</gallery>
PHP代码
$doc = new DOMDocument();
$doc->formatOutput = TRUE;
$doc->preserveWhiteSpace = FALSE;
$xPath = new DOMXPath($doc);
$doc->load('../Event_gallery.xml');
$query = sprintf('//pictures[./picture[@id="%s"]]', 38);
foreach ($xPath->query($query) as $node) {
$node->parentNode->removeChild($node);
}
$doc->save('../Event_gallery.xml');
我认为xpath工作不正常。控制不在foreach
答案 0 :(得分:0)
问题是您在 之后加载文档 ,并将文档传递给DOMXPath
。
更改
$xPath = new DOMXPath($doc);
$doc->load('../Event_gallery.xml');
到
$doc->load('../Event_gallery.xml');
$xPath = new DOMXPath($doc);
然后它应该工作。
要仅删除具有给定id而不是整个父级的图片元素,请将XPath更改为
//pictures/picture[@id="38"]