Nov 11, 2009

Parsing the XML/RSS in JavaScript

After reading James' post about how he used the simplexml method of PHP to parse through his XML results, I decided to explain how I used JavaScript to parse my results. It is kind of complex, but I don't know any easier way to do it. Basically what you have to do is get the whole RSS response back from the API you call and then you have to look at it and decide what you want to get out of it. Once you know what you want (i.e. the title or the author or whatever it is) you then need to write the JavaScript code that will get it automatically every time the API is called with your AJAX. In the example I did with the class blog that counts everyone's blogs and comments, I needed to get the author names back from the blogger API. To do this in JavaScript I did the normal AJAX stuff like Professor Drake showed us in class to get the RSS response from the blogger API, but instead of just placing the results into a div on the page somewhere or in an alert box, I took those results and parsed through them to get just the author names out of it. To do that, I just passed the request into a function like this:



This takes the request.responseXML and passes it to a function I created called readBlogFeed. In that function I executed the following code (which is the tricky part):



Now I had a lot more code doing other things in my actual project, but basically the getElementsByTagName and the whole childNodes stuff is what you need. Professor Drake's stuff was done the same way with all the childNode stuff, so look at that too for more help. What you'll get in result from this function is a list of all the names of authors from the blog site and the "return" command will send those names back to the original function that called it, which is where I said:



So now those results will be placed in the div I called "blogNames" on my main HTML page. Like I said, it gets a lot more complex, but this should give you some idea of how to get the information you want from your RSS response from the API you are using in your own project(s).

You can see the results I talked about in more detail in my other posts on my people account Website at http://people.emich.edu/mmager/449/.

Hope this helps!

1 comment:

  1. Thank you for the tips Matt.
    they were really helpful. It would be really great if you made that post a week earlier :). Actually we had to modify your code a little bit in order to work. For example we had to be careful with the child parent relationship.

    ReplyDelete