我正在尝试使用javascript解析Reddit的XML file,并且我无法从具有命名空间的节点检索属性。我想获得以下网址
<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>
我迷了你能提供任何帮助吗?
答案 0 :(得分:1)
.getElementsByTagName('media:thumbnail')
为我工作=)[在Chrome中]虽然我应该注意到您引用的特定XML文件,但前几个项目不包含<media:thumbnail>
标记。
你应该检查调用getElementsByTagName
之前试图拉出第n个(或者你的情况是第0个)元素的结果长度,因为这会导致错误
e.g。
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
}