2014-10-29 114 views
0

我有一些這樣的XML:刪除父節點從XML在PHP

<tree path="Masters"> 
    <item id="Masters\2014" name="2014" isFolder="true" path="Masters\2014" > 
     <item id="Masters\2014\Brochures" name="Brochures" isFolder="true" path="Masters\2014\Brochures" > 
      <item id="Masters\2014\Brochures\PLEASE DO NOT COPY" name="PLEASE DO NOT COPY" isFolder="true" path="Masters\2014\Brochures\PLEASE DO NOT COPY" > 
       <item id="a4e6f520-9b26-42c0-af92-bbd17ab6e8b6" name="00001" isFolder="false" path="Masters\2014\Brochures\PLEASE DO NOT COPY\00001.xml" > 
        <fileInfo fileSize="141.23 Kb"></fileInfo> 
       </item> 
       <item id="6b8cbff5-cf03-4d2c-9931-bb58d7f3ff8a" name="00002" isFolder="false" path="Masters\2014\Brochures\PLEASE DO NOT COPY\00002.xml" > 
        <fileInfo fileSize="192.19 Kb"></fileInfo> 
       </item> 
      </item> 
      <item id="65773008-4e64-4316-92dd-6a535616ccf6" name="Sales Brochure A4" isFolder="false" path="Masters\2014\Brochures\Sales Brochure A4.xml" > 
       <fileInfo fileSize="34.38 Kb"></fileInfo> 
      </item> 
     </item> 
    </item> 
</tree> 

我需要刪除所有節點(包括小孩),其中屬性name正則表達式匹配/^[0-9]{5,6}$/(它是一個5或6數字長名稱),也刪除其父母

除此之外,我還需要刪除任何具有屬性isFolder設置爲false的元素。

我到目前爲止的代碼是:

<?php 

$simple_xml = simplexml_load_string($xml); 

//Foreach item tag 
foreach($simple_xml->xpath('//item') as $item) { 

    //This correctly identifies the nodes 
    if(preg_match('/^[0-9]{5,6}$/', $item->attributes()->name)) { 

     //This doesn't work. I'm guessing chaining isn't possible? 
     $dom = dom_import_simplexml($item); 
     $dom->parentNode->parentNode->removeChild($dom); 


    } else { 

     //This correctly identifies the nodes 
     if($item->attributes()->isFolder == 'false') { 

      //This part works correctly and removes the nodes as required 
      $dom = dom_import_simplexml($item); 
      $dom->parentNode->removeChild($dom); 

     } 

    } 

} 

//At this point $simple_xml should contain the rebuilt xml tree in simplexml style 

?> 

由於可以從評論中可以看出,我有isFolder部分工作,我需要,但我似乎不能當刪除父節點項目節點的屬性name的值爲5或6位數的長名稱。

在此先感謝您的幫助。

回答

1

主要問題是您試圖從祖父母中刪除<item>節點。下面的代碼已被重新​​考慮,所以父母將從祖父母中刪除。

$simple_xml = simplexml_load_string($xml); 
foreach ($simple_xml->xpath('//item') as $item) { 
    if (preg_match('/^[0-9]{5,6}$/', $item['name'])) { 
    $dom = dom_import_simplexml($item); 
    $parent = $dom->parentNode; 
    if ($parent && $parent->parentNode) { 
     $parent->parentNode->removeChild($parent); 
    } 
    } else if ($item['isFolder'] == 'false') { 
    $dom = dom_import_simplexml($item); 
    $dom->parentNode->removeChild($dom); 
    } 
} 
+0

完美!感謝您的及時解決方案。我知道這會很簡單。 – PaulSkinner 2014-10-29 16:03:35