2013-09-29 34 views
1

我有一個包含一些像這樣的xml文件channels.xml得到xml文件中的一個標籤的內容。無法使用JavaScript

<StreamingChannelList xmlns:i="http://www.w3.org/2001/XMLSchema-instance">  
<StreamingChannel> 
<Source xmlns:a="http://schemas.datacontract.org/2004/07"> 
<a:directUrl> 
rtsp://10.232.15.90/PSIA/Streaming/Channels/F36AFF8A-79A0-4C80-BED7-4EF795B4EDB0 
</a:directUrl> 
</Source> 
</StreamingChannel> 
</StreamingChannelList> 

我需要的內容:directUrl標籤和我寫了下面的JavaScript,但無法獲得content.can任何標籤告訴我什麼是錯的代碼(特別是最後4行)? FYI:在Windows上使用Safari瀏覽器

<script> 
if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xmlhttp.open("GET","channels.xml",false); 
xmlhttp.send(); 
xmlDoc=xmlhttp.responseXML; 

var StreamingChannel=xmlDoc.getElementsByTagName("StreamingChannel"); 
var Source=StreamingChannel[0].getElementsByTagName("Source"); 
var directUrl=Source[0].getElementsByTagName("a:directUrl"); 
document.write("<td>"+directUrl[0].childNodes[0].nodeValue+"</td>"); 
</script> 
+0

似乎在Firefox中正常工作 –

回答

0

Safari瀏覽器有前面帶元素的名稱,a:directUrl問題。

你需要的是getElementsByTagName特殊前綴的版本,即getElementsByTagNameNS,有作爲第一個參數的命名空間的URI。
https://developer.mozilla.org/en-US/docs/Web/API/element.getElementsByTagNameNS

所以通話將不得不

var directUrl = Source[0].getElementsByTagNameNS("http://schemas.datacontract.org/2004/07", "directUrl"); 

,然後它的作品,至少在Safari和Firefox。
現在的問題是,我沒有能夠在IE中測試,因爲IE拒絕做HTTP請求,但有傳言說,IE不知道getElementsByTagNameNS。因此,你會需要像

var directUrl; 
if (document.getElementsByTagNameNS) 
    directUrl = Source[0].getElementsByTagNameNS("http://schemas.datacontract.org/2004/07", "directUrl"); 
else 
    directUrl = Source[0].getElementsByTagName("a:directUrl"); 

不知道這會的工作,雖然;這可能需要一些工作。就像我說的,我不能讓IE在這裏工作。

+0

將調用改爲var directUrl = Source [0] .getElementsByTagNameNS(「http://schemas.datacontract.org/2004/07」,「directUrl」); – jaggi

+0

改變調用'VAR directUrl後=源[0] .getElementsByTagNameNS( 「http://schemas.datacontract.org/2004/07」, 「directUrl」);',我能夠得到的標籤內容。感謝@Mr李斯特 – jaggi

+0

我發現,這是有可能得到一個:directUrl內容使用標籤的絕對位置。 'directUrl = StreamingChannel [I] .getElementsByTagName( 「源」)[0] .childNodes [0] .childNodes [0] .nodeValue;' – jaggi