2010-08-10 122 views
0

从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

问题将会是你您通过文档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"] 
+0

一件事我要删除节点图片仅供不是图片。这一次它删除图片。你能帮忙吗? – rajanikant 2010-08-10 10:35:54

+0

@rajanikant请参阅更新 – Gordon 2010-08-10 10:56:51