Web Analytics Made Easy -
StatCounter Parsing XML with JS - CodingForum

Announcement

Collapse
No announcement yet.

Parsing XML with JS

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Parsing XML with JS

    Hi all,
    can someone help me parse an xml thru js and display link, title, description and image from the following xml sample? please..


    <rss version="2.0">

    <channel>
    <title>gamesLeadRotator</title>
    <description>Games Lead Rotator Rss</description>
    <language>en-us</language>
    <link>www.gmaes.com</link>
    <copyright>Copyright 2009, All Rights Reserved.</copyright>
    <lastBuildDate>Thu, 26 Mar 2009 06:45:00 GMT</lastBuildDate>
    <ttl>60</ttl>

    <item>
    <title>Play Classic Solitaire</title>
    +
    <description>
    <img src="www.gmaes.com/games/solitaire.jpg" > Have great fun playing this classic game for free only Games! <br><a href="http://www.gmaes.com/games">Play Classic Solitaire</a> »
    </description>
    <link>http://www.gmaes.com/games</link>
    <guid>http://www.gmaes.com/games</guid>
    <pubDate/>
    </item>

    <item>
    <title>SCRABBLE Blast</title>

    <description>
    <img src="www.gmaes.com/games/scrabble_blast.jpg" > Put your word knowledge to the test in SCRABBLE Blast. <br><a href='http://www.gmaes.com/games'>Play SCRABBLE Blast</a> »
    </description>
    <link>http://www.gmaes.com/games</link>
    <guid>http://www.gmaes.com/games</guid>
    <pubDate/>
    </item>

    <item>
    <title>Bingo</title>

    <description>
    <img src="http://www.gmaes.com/games/bingo.jpg" > Play up to six cards at once and chat while you play. <br><a href='http://www.aol.co.uk/games'>Play Bingo</a> »
    </description>
    <link>http://www.gmaes.com/games</link>
    <guid>http://www.gmaes.com/games</guid>
    <pubDate/>
    </item>
    </channel>
    </rss>
    _______________________________________________________________________________________
    Thank the user for his/her helpful post by clicking on the button below the post :)

    Cheers :)
    ~ LSK ~

  • #2
    simple xml handling in javascript

    the code you posted is not valid xml, so it would be hard to parse it reliably...

    provided good input, try to use a few reusable functions to handle the repetitive parts.


    the images are inside the description, so you'll have to show the whole thing, or use valid markup inside the description tag...


    provided you have a regular rss file, something like this works:

    Code:
    <html><body><script>
    // helpers:
    
    function IOx(U) { // xml file loader
        var X = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
        X.open('GET', U, false);
        X.send('');
     return X.responseXML;
    }
    
    function kid(dad, kidTagName){var t=dad.getElementsByTagName(kidTagName); return t ? text(t[0]):""||""; }
    function text(elm){return elm.text || elm.textContent || "" ; }
    
    function harvest(it){ //display link, title, description and image
      return {
       link: kid(it, "link"),
       title:kid(it, "title"),
       description:kid(it, "description")
      };
    }
    
    
    // code for this app:
    var buffer=["<ul>"]; //hold the output efficiently
    var doc=IOx("rss.xml"); //load the xml document in the page's folder
    var allItems=doc.documentElement.getElementsByTagName("item"); //gather all items
    
    // make html:
    for(var i=0,mx=allItems.length;i<mx;i++){
      var it=harvest(allItems[i]);
      buffer.push( "<li><b>"+it.title.link(it.link)+ "</b> - "+it.description+"</li>"  );
    }
    
    document.body.innerHTML = buffer.join("\n")+"</ul>";
    
    // tested in IE8(both modes),FF3,Op,Ch,Sa(pc)
    </script></body></html>
    the output should probably go somewhere other than the body, but this is just a demo...
    Last edited by rnd me; Apr 14, 2009, 11:50 PM.
    Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

    Comment


    • #3
      Hi "rnd me",
      I am truly speechless buddy. Amazing talent. That worked like a charm. a million thanks to you. I have few last questions though. if i load an xml from the same server ( like "/apps/games.xml") it works fine. but if its an external xml (like "http://somedomain.com/some.xml") it does not seem to work.

      documentElement - does not work on IE6?

      why is that?

      Second one, how do I assign the output to an element in the body?

      Say i have, <div id="feedModule">(output here)</div>

      Please help...
      Last edited by lokeshshettyk; Apr 15, 2009, 05:59 AM.
      _______________________________________________________________________________________
      Thank the user for his/her helpful post by clicking on the button below the post :)

      Cheers :)
      ~ LSK ~

      Comment


      • #4
        Originally posted by lokeshshettyk View Post
        Hi "rnd me",
        I am truly speechless buddy. Amazing talent. That worked like a charm. a million thanks to you. I have few last questions though. if i load an xml from the same server ( like "/apps/games.xml") it works fine. but if its an external xml (like "http://somedomain.com/some.xml") it does not seem to work.

        documentElement - does not work on IE6?

        why is that?

        Second one, how do I assign the output to an element in the body?

        Say i have, <div id="feedModule">(output here)</div>

        Please help...
        ok. let's go in order:

        1. outside domains are never allowed, google "same origin" to find out why, and how to overcome.

        2. documentElement.
        try replacing my IOx function:

        Code:
        function IOx(U) { // xml file loader
            var X = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
            X.open('GET', U, false);
            X[COLOR="DarkGreen"].setRequestHeader('Content-Type', 'text/xml')[/COLOR]
            X.send('');
         return X.responseXML;
        }
        not sure that it will help. If you still can't get it, we can load the XML as text and feed it manually to an IE xml dom. This would bloat out code a bit, but it's nice to have universal compat. let me know if you still have trouble after above mod.


        3. Reaching id'd elements:
        Code:
        document.getElementById("feedModule").innerHTML=  buffer.join("\n")+"</ul>";
        Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

        Comment


        • #5
          Hi,
          None of the above worked . Not even assigning the output to and element. document.write (buffer.join("\n")); works fine. but i just can't assign this to an element.... Please help
          _______________________________________________________________________________________
          Thank the user for his/her helpful post by clicking on the button below the post :)

          Cheers :)
          ~ LSK ~

          Comment


          • #6
            Hey,
            I came up with a brand new script for myself. Everything works all good. The only problem now is to load a remote XML. That's everything. Please help
            _______________________________________________________________________________________
            Thank the user for his/her helpful post by clicking on the button below the post :)

            Cheers :)
            ~ LSK ~

            Comment


            • #7
              what do you mean by remote?

              anything off-site will need a server to break the same-origin restrictions imposed on javascript...
              Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

              Comment


              • #8
                alright RND
                I am finally here.

                Could you help me parse this xml pieace as a string?

                Code:
                <item><title><![CDATA[Play Classic Solitaire]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.agl.co.uk:10660/agluk/games/solitaire.jpg" /> Have great fun playing this classic game for free only on agl Games! <br /><a href="http://www.agl.co.uk/games">Play Classic Solitaire</a> »]]></description> <link><![CDATA[http://www.agl.co.uk/games]]></link><guid>http://www.agl.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[SCRABBLE Blast]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.agl.co.uk:10660/agluk/games/scrabble_blast.jpg" /> Put your word knowledge to the test in SCRABBLE Blast. <br /><a href="http://www.agl.co.uk/games">Play SCRABBLE Blast</a> »]]></description> <link><![CDATA[http://www.agl.co.uk/games]]></link><guid>http://www.agl.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Bingo]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.agl.co.uk:10660/agluk/games/bingo.jpg" /> Play up to six cards at once and chat while you play. <br /><a href="http://www.agl.co.uk/games">Play Bingo</a> »]]></description> <link><![CDATA[http://www.agl.co.uk/games]]></link><guid>http://www.agl.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Super Collapse! Puzzle Gallery]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.agl.co.uk:10660/agluk/games/puzzle_gallery.jpg" /> Can you remove all the blocks in the fewest possible moves? <br /> <a href="http://www.agl.co.uk/games">Play Super Collapse! Puzzle Gallery </a>»]]></description> <link><![CDATA[http://www.agl.co.uk/games]]></link><guid>http://www.agl.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Sudoku]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.agl.co.uk:10660/agluk/games/sudoku.jpg" /> Solve the mystery of the number grid with reasoning and patience.<br /><a href="http://www.agl.co.uk/games">Play Sudoku</a> »]]></description> <link><![CDATA[http://www.agl.co.uk/games]]></link><guid>http://www.agl.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Zenerchi]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.agl.co.uk:10660/agluk/games/zenerchi.jpg" /> Feeling stressed? Play this meditative mind game.<br /><a href="http://www.agl.co.uk/games">Play Zenerchi </a>»]]></description> <link><![CDATA[http://www.agl.co.uk/games]]></link><guid>http://www.agl.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Bookworm]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.agl.co.uk:10660/agluk/games/bookworm.jpg" /> Help the Bookworm chomp letters to make words and score points. Gobble up a faster-paced new action mode and make words up to 12 letters long.<br /><a href="http://www.agl.co.uk/games">Try Bookworm</a>]]></description> <link><![CDATA[http://www.agl.co.uk/games]]></link><guid>http://www.agl.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Alice Greenfingers]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.agl.co.uk:10660/agluk/games/alice.jpg" /> Build a blooming garden of flowers and vegetables, follow the trends and serve ripe crops at the town market.<br /> <a href="http://www.agl.co.uk/games">Play now</a> »]]></description> <link><![CDATA[http://www.agl.co.uk/games]]></link><guid>http://www.agl.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[3-Point Showdown]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.agl.co.uk:10660/agluk/games/3point_showdown.jpg" /> Show your stuff in this online sports game for sharp shooters.<br /><a href="http://www.agl.co.uk/games">Play now</a> »]]></description> <link><![CDATA[http://www.agl.co.uk/games]]></link><guid>http://www.agl.co.uk/games</guid> <pubDate></pubDate></item>

                and this is what i have got

                Code:
                <html>
                <head>
                <script type="text/javascript">
                
                function loadXMLDoc(txt) {
                	try {
                		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                		xmlDoc.async="false";
                		xmlDoc.loadXML(txt);
                	}
                	catch(e) { //Firefox, Mozilla, Opera, etc.
                		try {
                			parser= new DOMParser();
                			xmlDoc = parser.parseFromString(txt,"text/xml");
                		}
                		catch(e) {
                			alert(e.message);
                			return;
                		}
                	}
                	return xmlDoc;
                }
                
                function parseXML() {
                	var txt = '<item><title><![CDATA[Play Classic Solitaire]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.aol.co.uk:10660/aoluk/games/solitaire.jpg" /> Have great fun playing this classic game for free only on AOL Games! <br /><a href="http://www.aol.co.uk/games">Play Classic Solitaire</a> »]]></description> <link><![CDATA[http://www.aol.co.uk/games]]></link><guid>http://www.aol.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[SCRABBLE Blast]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.aol.co.uk:10660/aoluk/games/scrabble_blast.jpg" /> Put your word knowledge to the test in SCRABBLE Blast. <br /><a href="http://www.aol.co.uk/games">Play SCRABBLE Blast</a> »]]></description> <link><![CDATA[http://www.aol.co.uk/games]]></link><guid>http://www.aol.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Bingo]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.aol.co.uk:10660/aoluk/games/bingo.jpg" /> Play up to six cards at once and chat while you play. <br /><a href="http://www.aol.co.uk/games">Play Bingo</a> »]]></description> <link><![CDATA[http://www.aol.co.uk/games]]></link><guid>http://www.aol.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Super Collapse! Puzzle Gallery]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.aol.co.uk:10660/aoluk/games/puzzle_gallery.jpg" /> Can you remove all the blocks in the fewest possible moves? <br /> <a href="http://www.aol.co.uk/games">Play Super Collapse! Puzzle Gallery </a>»]]></description> <link><![CDATA[http://www.aol.co.uk/games]]></link><guid>http://www.aol.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Sudoku]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.aol.co.uk:10660/aoluk/games/sudoku.jpg" /> Solve the mystery of the number grid with reasoning and patience.<br /><a href="http://www.aol.co.uk/games">Play Sudoku</a> »]]></description> <link><![CDATA[http://www.aol.co.uk/games]]></link><guid>http://www.aol.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Zenerchi]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.aol.co.uk:10660/aoluk/games/zenerchi.jpg" /> Feeling stressed? Play this meditative mind game.<br /><a href="http://www.aol.co.uk/games">Play Zenerchi </a>»]]></description> <link><![CDATA[http://www.aol.co.uk/games]]></link><guid>http://www.aol.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Bookworm]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.aol.co.uk:10660/aoluk/games/bookworm.jpg" /> Help the Bookworm chomp letters to make words and score points. Gobble up a faster-paced new action mode and make words up to 12 letters long.<br /><a href="http://www.aol.co.uk/games">Try Bookworm</a>]]></description> <link><![CDATA[http://www.aol.co.uk/games]]></link><guid>http://www.aol.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[Alice Greenfingers]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.aol.co.uk:10660/aoluk/games/alice.jpg" /> Build a blooming garden of flowers and vegetables, follow the trends and serve ripe crops at the town market.<br /> <a href="http://www.aol.co.uk/games">Play now</a> »]]></description> <link><![CDATA[http://www.aol.co.uk/games]]></link><guid>http://www.aol.co.uk/games</guid> <pubDate></pubDate></item><item><title><![CDATA[3-Point Showdown]]></title><description><![CDATA[<img src="http://adpdev-lu05.dev.aol.co.uk:10660/aoluk/games/3point_showdown.jpg" /> Show your stuff in this online sports game for sharp shooters.<br /><a href="http://www.aol.co.uk/games">Play now</a> »]]></description> <link><![CDATA[http://www.aol.co.uk/games]]></link><guid>http://www.aol.co.uk/games</guid> <pubDate></pubDate></item>';
                	xmlDoc = loadXMLDoc(txt);
                	var buffer = ["<a title='previous' href='#' class='previous'>Prev</a><ul>"]; // to hold the output
                	var allItems = xmlDoc.getElementsByTagName("item");
                
                	alert (allItems.length); // Says ZERO ?????????????
                	for(var i=0; i<allItems.length; i++) {
                		var titleText = allItems[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
                		var descText = allItems[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
                		var linkText = allItems[i].getElementsByTagName("link")[0].childNodes[0].nodeValue;
                		// alert (descText);
                		var descArr = descText.split("/>");
                		var imgText = descArr[0]+"/>";
                		var descText = descArr[1]+"/>";
                		var linkText = descArr[2];
                		var disp = "<div style>" + imgText + "</div><div>" + titleText + "</div><div>" + descText + "" +linkText + "</div>";		
                		// var guidText = allItems[i].getElementsByTagName("guid")[0].childNodes[0].nodeValue;
                		buffer.push("<li>" + disp + "</li>");
                	}
                	document.getElementById('feedData').innerHTML = buffer.join("\n")+"</ul><a title='next' href='#' class='next'>Next</a>";
                	// document.body.innerHTML = buffer.join("\n")+"</ul><a title='next' href='#' class='next'>Next</a>";
                	// document.getElementById("talent").innerHTML = buffer.join("\n")+"</ul><a title='next' href='#' class='next'>Next</a>";
                	// document.getElementById("talent").innerHTML = buffer.join("\n")+"</ul><a title='next' href='#' class='next'>Next</a>";
                	// document.write (buffer.join("\n")+"</ul><a title='next' href='#' class='next'>Next</a></div>");
                    // document.getElementById('talent').appendChild(div);
                	// document.getElementById('container').innerHTML = buffer.join("\n")+"</ul><a title='next' href='#' class='next'>Next</a></div>";
                	// document.getElementById('talent').innerHTML = "Hiii";
                	// return buffer.join("\n")+"</ul><a title='next' href='#' class='next'>Next</a></div>";
                }
                </script>
                </head>
                
                <body>
                	<div class="carousel" id="feedData"><script language="javascript">parseXML();</script></div>
                </body>
                </html>
                Last edited by lokeshshettyk; Apr 20, 2009, 06:33 AM.
                _______________________________________________________________________________________
                Thank the user for his/her helpful post by clicking on the button below the post :)

                Cheers :)
                ~ LSK ~

                Comment


                • #9
                  xmlDoc = loadXMLDoc(txt).documentElement; ?
                  Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com

                  Comment


                  • #10
                    did not work, I am stuck!
                    _______________________________________________________________________________________
                    Thank the user for his/her helpful post by clicking on the button below the post :)

                    Cheers :)
                    ~ LSK ~

                    Comment


                    • #11
                      Thank you all, i figured it out myself
                      _______________________________________________________________________________________
                      Thank the user for his/her helpful post by clicking on the button below the post :)

                      Cheers :)
                      ~ LSK ~

                      Comment

                      Working...
                      X