2010-08-10 173 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