0

I'm trying to parse Reddit's XML file with javascript and im having trouble retrieving an attribute from a node with a namespace. I want to get the following URL

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

What I tried so far but none of these have worked:

<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>

I'm lost can you offer any help?

1 Answer 1

1
.getElementsByTagName('media:thumbnail')

worked for me =) [In Chrome] Though I should note that on the particular XML file you referenced, the first few items do not contain <media:thumbnail> tags.

You should check the length of the result of the call to getElementsByTagName BEFORE trying to pull out the nth (or in your case the 0th) element, as that will cause an error.

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.