2015-11-05 52 views
0

我有下面的示例XML文件:檢查如果XML節點的父母有特殊attibute

<?xml version="1.0" encoding="utf-8" ?> 
<categories> 
    <category id="1" name="Car"> 
     <category id="12" name="Electrical"> 
      <category id="18" name="On-Road"> 
       <category id="127" name="Carisma"></category> 
       <category id="128" name="HPI - Maverick"></category> 
       <category id="452" name="HSP"></category> 
       <category id="130" name="Other"></category> 
      </category> 
      <category id="16" name="Off-Road"> 
       <category id="132" name="HPI - Maverick"></category> 
       <category id="225" name="Carisma"></category> 
       <category id="315" name="HSP"></category> 
       <category id="420" name="Other"></category> 
      </category> 
     </category> 
    </category> 
</categories> 

我需要的是所有子節點白衣值specifi ID的所有父節點。

例如,如果id的值是128, 那麼它會響應:汽車/電氣/公路上/ HPI - 小牛

如果id的值是12,則它會響應汽車/電氣

並繼續...

我設法讓與值(低於)特定ID的節點,但我無法弄清楚如何從選擇的節點得到父母鏈。

<?php 
$file = "http://www.localhost.com/categories.xml"; 

$microline = new SimpleXMLElement($file, null, true); 

foreach($microline as $cat){ 
    if ($cat->children['id'] = $catid) { 

     $current_cat_name = $cat->xpath("//*[@id=$catid]/@name")[0]; 
     echo $current_cat_name; 
    } 
} 
unset($microline); 
?> 

回答

0

如果您使用XPath //*[@id=$catid]/ancestor-or-self::category/@name然後你把所有的屬性值,並只需要在PHP中的反斜槓字符將它們串聯。

因此,

$xml = <<<'EOB' 
<categories> 
    <category id="1" name="Car"> 
     <category id="12" name="Electrical"> 
      <category id="18" name="On-Road"> 
       <category id="127" name="Carisma"></category> 
       <category id="128" name="HPI - Maverick"></category> 
       <category id="452" name="HSP"></category> 
       <category id="130" name="Other"></category> 
      </category> 
      <category id="16" name="Off-Road"> 
       <category id="132" name="HPI - Maverick"></category> 
       <category id="225" name="Carisma"></category> 
       <category id="315" name="HSP"></category> 
       <category id="420" name="Other"></category> 
      </category> 
     </category> 
    </category> 
</categories> 
EOB; 

$root = new SimpleXMLElement($xml); 
$id = 127; 
$cats = $root->xpath("//*[@id=$id]/ancestor-or-self::category"); 

$path = implode('/', array_map(function($a) { return $a['name']; }, $cats)); 

echo $path; 

會輸出Car/Electrical/On-Road/Carisma

+0

感謝事實,它像一個魅力@Martin Honnen – tufanayd