Page 1 of 2 12 LastLast
Results 1 to 10 of 15

Thread: Parsing data from an xml file

  1. #1
    Join Date
    Feb 2008
    Posts
    74
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Question Parsing data from an xml file

    Hello,

    I'm trying to parse my data from an xml file now and print it out on the page based on date from my existing code. I have that working, with each item formatted the same way on the page What I'd like to do now is alter it a bit to make the most recent (the item listed on the top of the page) formatted differently and the rest of them as it is now. Something like - (if 1st <li> then build html like this else build html like that) I hope this makes sense.

    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <books>
        <book title="CSS Mastery" imageurl="http://cdn.net.tutsplus.com/045_LoadXMLWithJquery/images/css.jpg">
            <description>
                08/01/2010 - Content
            </description>
        </book>
    
        <book title="Professional ASP.NET" imageurl="http://cdn.net.tutsplus.com/045_LoadXMLWithJquery/images/asp.jpg">
            <description>
                08/02/2010 - Content
            </description>
        </book>
    
        <book title="Learning jQuery" imageurl="http://cdn.net.tutsplus.com/045_LoadXMLWithJquery/images/lj.jpg">
            <description>
                08/03/2010 - Content
            </description>
        </book>
    	
    	<book title="Learning jQuery" imageurl="http://cdn.net.tutsplus.com/045_LoadXMLWithJquery/images/lj.jpg">
            <description>
                08/04/2010 - Content
            </description>
        </book>
    	
    	<book title="Learning jQuery" imageurl="http://cdn.net.tutsplus.com/045_LoadXMLWithJquery/images/lj.jpg">
            <description>
                08/05/2010 - Content
            </description>
        </book>
        
    </books>
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Load XML With jQuery</title>
        <script src="jquery-1.2.6.js" type="text/javascript"></script>
        <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
    
        <script type="text/javascript">
        
        $(document).ready(function()
          {
    		  
    		  /*Gets current date*/
    			var m_names = new Array("January", "February", "March",
    			"April", "May", "June", "July", "August", "September",
    			"October", "November", "December");
    			
    			var date = new Date();
    			/*var curr_date = d.getDate();*/
    			var curr_date = 3;
    			var curr_month = date.getMonth();
    			var curr_year = date.getFullYear();
    	
    
            $.get('myData.xml', function(d){
           /* $('body').append('<h1> Title</h1>');*/
            $('#col-a').append('<ul id="tips"/>');
    
            $(d).find('book').each(function(){
    	
                var $book = $(this); 
                var title = $book.attr("title");
                var description = $book.find('description').text();
                var imageurl = $book.attr('imageurl');
    			
                var html = '<li class="tipItem" style="list-style:none;display: none; li">';
                html += '<img class="bookImage" alt="" src="' + imageurl + '" /> ';
                html += '<p class="title">' + title + '</p>';
                html += '<p> ' + description + '</p>' ;
                html += '</li>';
    
                $('ul').append($(html));
    		
    		});
    
    				var tips = $('#tips .tipItem');
    			  
    				tips.each(function(i) {
    					if (curr_month == 8 && curr_date <= i){
    						$(this).hide();
    					  } else {
    						  $(this).show();
    					  } 
    				});
    				
    				tips = $.makeArray(tips);
    				tips.reverse();
    				$(tips).appendTo(document.getElementById('tips')
    				);
    			
    
        });
    });
    	
    	
    	
    	
        </script>
    
    </head>
    <body>
    <div id="col-a"></div>
    </body>
    </html>

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Replace:

    Code:
    				$(tips).appendTo(document.getElementById('tips')
    				);
    with:

    Code:
    				$(tips).appendTo(document.getElementById('tips')).each(function(){
    					if(this.style.display !== 'none'){
    						$(this).addClass('theFirst');
    						return false;
    					}
    				});
    Now the first displayed tip li will have a class name of 'theFirst'. So, for example, you can add this rule to (preferably the end of) your stylesheet:

    Code:
    .theFirst .title {
    	color: red;
    }
    Full code of my working local mock up:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Load XML With jQuery</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <link href="http://cdn.net.tutsplus.com/045_LoadXMLWithJquery/StyleSheet.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
    .theFirst .title {
    	color: red;
    }
    </style>
        <script type="text/javascript">
        
        $(document).ready(function()
          {
    		  
    		  /*Gets current date*/
    			var m_names = new Array("January", "February", "March",
    			"April", "May", "June", "July", "August", "September",
    			"October", "November", "December");
    			
    			var date = new Date();
    			/*var curr_date = d.getDate();*/
    			var curr_date = 3;
    			var curr_month = date.getMonth();
    			var curr_year = date.getFullYear();
    	
    
            $.get('myData.xml', function(d){
           /* $('body').append('<h1> Title</h1>');*/
            $('#col-a').append('<ul id="tips"/>');
    
            $(d).find('book').each(function(){
    	
                var $book = $(this); 
                var title = $book.attr("title");
                var description = $book.find('description').text();
                var imageurl = $book.attr('imageurl');
    			
                var html = '<li class="tipItem" style="list-style:none;display: none; li">';
                html += '<img class="bookImage" alt="" src="' + imageurl + '" /> ';
                html += '<p class="title">' + title + '</p>';
                html += '<p> ' + description + '</p>' ;
                html += '</li>';
    
                $('ul').append($(html));
    		
    		});
    
    				var tips = $('#tips .tipItem');
    			  
    				tips.each(function(i) {
    					if (curr_month == 8 && curr_date <= i){
    						$(this).hide();
    					  } else {
    						  $(this).show();
    					  } 
    				});
    				
    				tips = $.makeArray(tips);
    				tips.reverse();
    				$(tips).appendTo(document.getElementById('tips')).each(function(){
    					if(this.style.display !== 'none'){
    						$(this).addClass('theFirst');
    						return false;
    					}
    				});
        });
    });
    	
    	
    	
    	
        </script>
    
    </head>
    <body>
    <div id="col-a"></div>
    </body>
    </html>
    Note: I'm using the latest 1.4x version of jQuery. But this also works with the 1.2.6 version you appear to be using. 1.4x is much more efficient though. there are some minor differences, none that affect this code.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Feb 2008
    Posts
    74
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default

    Thanks John,
    This is close, I actually wanted to rebuild the html in a different format as well. So essentially, I would have something like:

    If(whatever = the first li) {
    var html = '<li class="tipItem" style="list-style:none;display: none; li">';
    html += '<p class="title">' + title + '</p> ';
    html += '<img class="bookImage" alt="" src="' + imageurl + '" />';
    html += '<p> ' + description + '</p>' ;
    html += '<p> ' + description + '</p>' ;
    html += '</li>';

    } else {
    var html = '<li class="tipItem" style="list-style:none;display: none; li">';
    html += '<img class="bookImage" alt="" src="' + imageurl + '" /> ';
    html += '<p class="title">' + title + '</p>';
    html += '<p> ' + description + '</p>' ;
    html += '</li>';

    }

    Also, What is needed for this to work in IE?

  4. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    It's funny that you should use the word 'rebuild', as that would probably be easier given the current flow of your code. What your snippet shows however is building it differently to begin with. The easiest way to rebuild would be to maintain a reference to the data:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Load XML With jQuery</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <link href="http://cdn.net.tutsplus.com/045_LoadXMLWithJquery/StyleSheet.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
    .theFirst .title {
    	color: red;
    }
    </style>
        <script type="text/javascript">
        
        $(document).ready(function()
          {
    		  
    		  /*Gets current date*/
    			var m_names = new Array("January", "February", "March",
    			"April", "May", "June", "July", "August", "September",
    			"October", "November", "December");
    			var bookdata;
    			var date = new Date();
    			/*var curr_date = d.getDate();*/
    			var curr_date = 3;
    			var curr_month = date.getMonth();
    			var curr_year = date.getFullYear();
    	
    
            $.get('myData.xml', function(d){
           /* $('body').append('<h1> Title</h1>');*/
            $('#col-a').append('<ul id="tips"/>');
    	bookdata = $(d).find('book');
            bookdata.each(function(i){
    	
                var $book = bookdata.eq(i);
                var title = $book.attr("title");
                var description = $book.find('description').text();
                var imageurl = $book.attr('imageurl');
    			
                var html = '<li class="tipItem" style="list-style:none;display: none;">';
                html += '<img class="bookImage" alt="" src="' + imageurl + '" /> ';
                html += '<p class="title">' + title + '</p>';
                html += '<p> ' + description + '</p>' ;
                html += '</li>';
    
                $('ul').append($(html).data('data_book', i));
    		
    		});
    
    				var tips = $('#tips .tipItem');
    			  
    				tips.each(function(i) {
    					if (curr_month == 8 && curr_date <= i){
    						$(this).hide();
    					  } else {
    						  $(this).show();
    					  } 
    				});
    				
    				tips = $.makeArray(tips);
    				tips.reverse();
    				$(tips).appendTo(document.getElementById('tips')).each(function(){
    					if(this.style.display !== 'none'){
    						var theFirst = $(this);
    						var idx = theFirst.data('data_book');
    						var $book = bookdata.eq(idx);
    						var title = $book.attr("title");
    						var description = $book.find('description').text();
    						var imageurl = $book.attr('imageurl');
    							
    						var html = '<li class="tipItem" style="list-style:none;">';
    						html += '<p class="title">' + title + '</p> ';
    						html += '<img class="bookImage" alt="" src="' + imageurl + '" />';
    						html += '<p> ' + description + '</p>' ;
    						html += '<p> ' + description + '</p>' ;
    						html += '</li>';
    						theFirst.remove();
    				
    						$('ul').prepend($(html).data('data_book', idx).addClass('theFirst'));
    						return false;
    					}
    				});
        });
    });
    	
    	
    	
    	
        </script>
    
    </head>
    <body>
    <div id="col-a"></div>
    </body>
    </html>
    About IE - Works fine live. Locally it's a blank page.

    Note1: Depending upon how an AJAX routine is written (if it lacks an IE 7+ fall back to Active X for local implementations, which is sort of dishonest anyway), IE 7 and up will block it locally for security reasons. Chrome can too, though not all the time. For these and other reasons I test all my AJAX stuff on my local host sandbox (I use WAMP). It's also good for some frame and iframe, and communication between windows things, as these are all cross domain sensitive. In some browsers when run locally if all pages and resources aren't in the same folder they may be seen as on different domains.

    Same thing (folders seen as domains) for Chrome and AJAX I think. Firefox can do this with frames/iframes. For IE and AJAX it's a slightly different mechanism, but amounts to the same thing.

    Note2: Since an image(s) is/are involved, there might be problems in IE if the image hasn't fully loaded yet before the li is removed. If so, a workaround can be devised.
    Last edited by jscheuer1; 09-07-2010 at 02:43 PM. Reason: English usage - later add info and minor code improvement
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  5. #5
    Join Date
    Feb 2008
    Posts
    74
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default

    This Perfect!!!! Thanks so much John! This is exactly what I was looking for. Also, thanks for the tip on the localhost, I never thought about that factor.
    Last edited by bigalo; 09-08-2010 at 03:39 PM.

  6. #6
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I'm not sure about perfect. Nobody/nothing is. Anyways, here's how I would write it:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Load XML With jQuery</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <link href="http://cdn.net.tutsplus.com/045_LoadXMLWithJquery/StyleSheet.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
    .theFirst .title {
    	color: red;
    }
    </style>
    <script type="text/javascript">
    
    jQuery(function($){
    
    	/* Set Variables */
    	var m_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    	bookdata, bookHTML = [], date = new Date(), /* curr_date = d.getDate(), */curr_date = 3, curr_month = date.getMonth(),
    	curr_year = date.getFullYear(), $book, title, description, imageurl, idx, firstCompleted = false;
    
    
    	$.get('myData.xml', function(d){
    		/* $('body').append('<h1> Title</h1>'); */
    		$('#col-a').append('<ul id="tips"/>');
    		bookdata = $.map($(d).find('book'), function(n){return $(n);}).reverse();
    		$.each(bookdata, function(i){
    			if(curr_month === 8 && i + 1 >= curr_date){
    				$book = bookdata[i];
    				title = $book.attr("title");
    				description = $book.find('description').text();
    				imageurl = $book.attr('imageurl');
    
    				if(firstCompleted){
    					bookHTML.push(['<li class="tipItem" style="list-style:none;">',
    					'<img class="bookImage" alt="" src="' + imageurl + '" /> ',
    					'<p class="title">' + title + '</p>',
    					'<p> ' + description + '</p>',
    					'</li>'].join(''));
    				} else {
    					bookHTML[0] = ['<li class="tipItem theFirst" style="list-style:none;">',
    					'<p class="title">' + title + '</p> ',
    					'<img class="bookImage" alt="" src="' + imageurl + '" />',
    					'<p> ' + description + '</p>',
    					'<p> ' + description + '</p>',
    					'</li>'].join('');
    					firstCompleted = true;
    				}
    			}
    		});
    
    		$('ul').append(bookHTML.join(''));
    	});
    });	
    </script>
    
    </head>
    <body>
    <div id="col-a"></div>
    </body>
    </html>
    Notes: This also gets rid of any possibility that IE will have to deal with loading images being removed (something it often doesn't react well to).

    There's one thing about this that disturbs me, the curr_date and how that and the curr_month relate to the selecting of what content to show. In your example you chose an arbitrary number that suited the xml file's contents for the date and hard coded the expected month # into the if statement. I've followed suit above.

    It remains to be seen if, when actually using the live date, this will be workable. I'm imaging though that the value in each xml book element that is currently in the description tags, ex:

    Code:
        <book title="CSS Mastery" imageurl="http://cdn.net.tutsplus.com/045_LoadXMLWithJquery/images/css.jpg">
            <description>
                08/01/2010 - Content
            </description>
        </book>
    could be parsed (would require at least some additional code*) in order to get things to work out in a real example of this. Doing so probably will also require tweaking of the if:

    Code:
    if(curr_month === 8 && i + 1 >= curr_date)
    I've tried to preserve variables that are not in use but could be, as well as the commented out sections of the code from your initial example that could still be used for something. The date part for sure. I'm not certain what exactly you were going for with the <h1> Title</h1> thing. But I can imagine a few scenarios. You might want to prepend, rather than append it to the body.



    *I have what appears to be a solid idea for parsing the date for the description and using it to determine which 'books' get shown.
    Last edited by jscheuer1; 09-08-2010 at 04:08 AM. Reason: add info
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. #7
    Join Date
    Feb 2008
    Posts
    74
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default

    Thanks so much John,

    One other question. I'll probably need to use CDATA in my xml file. I tried to parse it out and it's not working correctly. Is there something in the code that I need to adjust to use CDATA?

    Code:
    <tiplink><![CDATA[<a name="" href="#">test link</a>]]></tiplink>
    I think I read somewhere that you would have to use a code snippet like similar to this to parse it out:

    Code:
    $(function(){
    	
    	var xmlDoc;
    	
    	$.ajax({
    		type: "GET",
    		url: "product-info.xml",
    		dataType: ($.browser.msie) ? "text" : "xml",
    		global: true,
    		cache: false,
    		success: setUpXml
    	});
    	
    	function setUpXml(data){
    		
    		if ( $.browser.msie ) {
    			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    			xmlDoc.async = false;
    			xmlDoc.loadXML(data);
    		}else{
    			xmlDoc = data;
    		}
    	
    		xmlDoc = $(xmlDoc);
    		yourfunction();
    	}
    Is that the case, if so, how would I do that with my existing code?

  8. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I see the problem. Where are you getting your information from as to the workaround?
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  9. #9
    Join Date
    Feb 2008
    Posts
    74
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default

    That ideas was just an idea. I'll be fine with what I currently have. Thanks anyway.

  10. #10
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Wait a minute, I don't see the problem. IE was caching the xml file for some reason. You can just use a regular link tag and get the href off of it.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •