user2493628
user2493628

Reputation: 13

Reading from XML

I used this code to get the title on my page from an XML file. Now, I want to display the description for the corresponding titles which is also present in the same XML file. How do I do that?

        var queryObj = new Object();
        var querystring = location.search.replace('?', '');
        var vars = querystring.split("&");
        for (var i = 0; i < vars.length; i++) 
        {
            var pair = vars[i].split('=');
            var key = pair[0];
            var value = pair[1]; 
            var value = decodeURI(value);
            queryObj[key] = value;

        }

        if(queryObj["activity"] != "" && queryObj["phase"] != "")
        {
            $("#TaskTitle").html(queryObj['phase']+": "+queryObj['activity']);
        }

Upvotes: 1

Views: 129

Answers (2)

krishwader
krishwader

Reputation: 11381

Consider I have an XML like this :

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book> ..so on
</catalog>

I'd store this in a string, then run parseXML() over it, which I'd push in a variable like this :

var xmlDoc= $.parseXML(myXmlString)

I could now this use this xmlDoc variable as a DOM object and traverse through it, if needed by passing it to $() as an argument.

$(xmlDoc)

Now, you could read up on find(), closest() etc and learn up on how you traverse in jQuery.

For example, if i want to get the author of the book XML developers guide, which lies in a <book> section with id #bk101, I'd do this :

$(xmlDoc).find("#bk101").find("author") 

             //OR

$(xmlDoc).find("#bk101 author") 

             //OR

$("#bk101", xmlDoc).find("author")

That's it. Here's a demo : http://jsfiddle.net/hungerpain/N3mYa/

Upvotes: 3

Praveen
Praveen

Reputation: 56539

Try using jQuery.parseXML(), which parses a string into an XML document.

Upvotes: 0

Related Questions