2011-10-29 48 views
0

我試圖用javascript解析Reddit的XML file,我無法從具有名稱空間的節點檢索屬性。我想下面的網址如何在javascript中使用名稱空間獲取節點的屬性?

<media:thumbnail url="http://f.thumbs.redditmedia.com/LdOsi1MnWuzGvbDq.jpg"/>

我試了一下,到目前爲止,但這些都沒有工作:

<script type="text/javascript"> 
//...XMLHttpRequest... 
      var items = data.getElementsByTagName("item"); 

      for (var i = 0; i < items.length; i++) { 
       var item = items[i]; 

       //titleNode and title work fine 
       var titleNode = item.getElementsByTagName("title")[0]; 
       var title = titleNode.firstChild.data; 

       //the following don't work, they actually cause the google chrome extension to stop working :(

       //attempt 1 
       thumbnail = item.getElementsByTagName('thumbnail')[0]; 

       //attempt 2 
       thumbnail = item.getElementsByTagName('media:thumbnail')[0]; 

       //attempt 3  
       thumbnail = item.getElementsByTagName('media', 'thumbnail')[0]; 

       //attempt 4 
       thumbnail = item.getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'thumbnail')[0]; 

       //attempt 5 
       thumbnail = item.getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'thumbnail')[0].getAttriubte("url"); 

       //attempt 6 
       thumbnail = item.getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'thumbnail')[0].firstChild.data; 

       document.write(thumbnail); 
      } 
</script> 

我迷路了,你能提供什麼幫助?

回答

1
.getElementsByTagName('media:thumbnail') 

爲我工作=)在Chrome中]雖然我要指出,你提到,前幾個項目不包含<media:thumbnail>代碼中的特定XML文件。

您應該檢查調用的結果的長度getElementsByTagName試圖拉出第n(或你的情況0)級元素,因爲這將導致錯誤。

例如

var thumbnail=null,mediaTs=item.getElementsByTagName('media:thumbnail'); 
if(mediaTs.length){ 
    thumbnail=mediaTs[0].getAttribute('url'); 
} 

//Later on 
if(thumbnail){ 
    //Do stuff with the string 
} 
相關問題