2010-08-06 96 views
0

我的XML文件被命名爲cgal.xml根據從XML刪除的屬性

<?xml version="1.0"?> 
<item> 
    <name><![CDATA[<img src="event_pic/pic1.jpg" />CALENDAR]]></name> 
    <description title="NAM ELIT AGNA, ENDRERIT SIT AMET, TINCIDUNT AC." day="13" month="8" year="2010" id="15"><![CDATA[<img src="events/preview/13p1.jpg" /><font size="8" color="#6c6e74">In Gladiator, victorious general Maximus Decimus Meridias has been named keeper of Rome and its empire by dying emperor Marcus Aurelius, so that rule might pass from the Caesars back to the people and Senate. Marcus\' neglected and power-hungry son, Commodus, has other ideas, however. Escaping an ordered execution, Maximus hurries back to his home in Spain, too l</font>]]></description> 
</item> 

和我的PHP函數是: -

$doc = new DOMDocument; 
      $doc->formatOutput = TRUE; 
      $doc->preserveWhiteSpace = FALSE; 

$doc->simplexml_load_file('../cgal.xml'); 
     foreach($doc->description as $des) 
      { 
       if($des['id'] == $id) { 
        $dom=dom_import_simplexml($des); 
        $dom->parentNode->removeChild($dom); 
       } 
      } 
      $doc->save('../cgal.xml'); 

ID動態傳遞

我想刪除節點根據ID

+1

你的問題是什麼?此外,也許這些問題之一可以幫助:http://stackoverflow.com/search?q=php+remove+node – 2010-08-06 12:10:55

回答

0

您不需要從SimpleXml加載或導入XML。您可以直接使用DOM加載它。另外,您可以像在問題updatin xml in php中那樣去除節點。只要改變XPath查詢閱讀

$query = sprintf('//description[@id="%s"]', $id); 

$query = sprintf('/item/description[@id="%s"]', $id); 

您還可以使用getElementById而不是一個XPath,如果你的XML驗證對DTD或模式,實際上ID定義爲一個XML ID。這在Simplify PHP DOM XML parsing - how?中有解釋。

0

那麼,首先,沒有DomDocument::simplexml_load_file()方法。無論是使用DOM文檔,或不...所以使用的DomDocument:

$doc = new DomDocument(); 
$doc->formatOutput = true; 
$doc->preserveWhiteSpace = true; 

$doc->loadXml(file_get_contents('../cgal.xml')); 

$element = $doc->getElementById($id); 
if ($element) { 
    $element->parentNode->removeChild($element); 
} 

這應該爲你做...

編輯:

戈登指出,這可能無法正常工作(我試了一下,確實不是所有的時間)......所以,你既可以:

$xpath = new DomXpath($doc); 
$elements = $xpath->query('//description[@id="'.$id.'"]'); 
foreach ($elements as $element) { 
    $element->parentNode->removeChild($element); 
} 

或者,使用SimpleXML,您可以在每個節點遞歸(執行少螞蟻,但更靈活):

$simple = simplexml_load_file('../cgal.xml', 'SimpleXmlIterator'); 
$it = new RecursiveIteratorIterator($simple, RecursiveIteratorIterator::SELF_FIRST); 
foreach ($it as $element) { 
    if (isset($element['id']) && $element['id'] == $id) { 
     $node = dom_import_simplexml($element); 
     $node->parentNode->removeChild($node); 
    } 
} 
+0

這將失敗,除非他有一個DTD或架構來驗證。 DOM不會識別ID屬性,而是將其視爲常規屬性。 – Gordon 2010-08-06 12:19:17

+0

謝謝@戈登,我用其他兩種可能性更新了我的答案...... – ircmaxell 2010-08-06 12:34:39