2013-02-12 91 views
0

我無法獲取xml元素的屬性值,因爲每次點擊鏈接id=中沒有值,但是當查看我的xml時有一個屬性值,爲什麼會發生這種情況我錯過了什麼?無法從PHP中的遞歸函數獲取xml元素屬性值?

這是我的PHP代碼:

<?php 
function parse_recursive(SimpleXMLElement $element, $level = 0) 
{ 
    $indent = str_repeat('', $level); 

    $value = trim((string) $element); 
    $children = $element->children(); 
    $attributes = $element->attributes(); 

    echo '<ul>'; 
    if(count($children) == 0 && !empty($value)) 
    { 
     if($element->getName() == 'GroupName'){ 
      echo '<li><a href="http://localhost:8080/test/test.php?id='; 
      if(count($attributes) > 0) 
      { 
       foreach($attributes as $attribute) 
       { 
        if($attribute->getName() == 'Id'){ 
         echo $attribute; 
        } 
       } 
      } 
      echo '">'.$element.'</a></li>'; 
     } 
    } 

    if(count($children)) 
    { 
     foreach($children as $child) 
     { 
      parse_recursive($child, $level+1); 
     } 
    } 
    echo '</ul>'; 
} 

$xml = new SimpleXMLElement('main.xml', null, true); 
parse_recursive($xml); 
?> 

這裏是我的XML結構:

enter image description here

回答

1

看來,你的代碼會爲GroupName元素只輸出任何東西:

if($element->getName() == 'GroupName'){ 

它只會輸出元素的屬性。

源XML中的單個GroupName沒有Id屬性。

+0

我看到這樣的問題是XML格式?,我也使用C#代碼創建XML, – MekeniKine 2013-02-12 03:40:26

+0

我不知道。這取決於你想要做什麼。你能否提供預期結果的樣本? – JLRishe 2013-02-12 03:51:46