Solved

Counting Elements In XML File With Jquery

Posted on 2008-10-30
6
4,977 Views
Last Modified: 2013-11-11
Hi,

I am currently working on a project for work that is of pretty big importance. I am using jQuery to read an XML file, I have no problems reading the file and pulling the information out.

What I am trying to do but failing is counting all of the elements in the XML file. I know it's something simple but searching Google just doesn't return anything but Xpath which is deprecated in the latest version of jQuery.

I just need to count the number of total XML elements there are in the XML file, by that I mean each instance of <item>. And I also want to pull out specific info from the XML file depending on what number it is. Say for example there are 4 blogs. I would like to be able to target the first item and only pull it's information out (title, blogurl, rssurl).

So if I wanted to pull out the fourth entry and their are four entries in the XML file, I would only want the information for the fourth element.


The XML File Is Out Layed Like This:

<directory>

      <item>

            <title>Blog Title</title>
            <image>img/shallowend_bg2.png</image>
            <rssurl>rss.xml</rssurl>
            <blogurl></blogurl>
            <contributors>
                  <contributor imageurl="thumbnail.png" profileurl="">
                  Contributor name
                  </contributor>            
            
                  <contributor imageurl="thumbnail.png" profileurl="">
                  Contributor name
                  </contributor>
            
                  <contributor imageurl="thumbnail.png" profileurl="">
                  Contributor name
                  </contributor>      
                  
                  <contributor imageurl="thumbnail.png" profileurl="">
                  Contributor name
                  </contributor>
            </contributors>

      </item>

Any help would be gratefully appreciated on this.
$.get("xml/directory.xml",{},function(xml) 
		{
		 // Return each item found in the XML file with a beginning attribute titled "item"
		 $('item',xml).each(function(i) 
		 {
			/* Variables */
			_id          = $(this).find("id").attr("id");
			_title       = $(this).find("title").text();       				  // Item title			
			_image       = $(this).find("image").text();       				  // Image title
			_rssurl      = $(this).find("rssurl").text();      				  // Rss url
			_blogurl     = $(this).find("blogurl").text(); 	   				  // Blog url
			_contributor = $(this).find("contributor").text(); 				  // Contributor Name
			_contributorimg = $(this).find("contributor").attr("imageurl");   // Contributor Image Location (url)
			_contributorpro = $(this).find("contributor").attr("profileurl"); // Controbutor Profile Location (url) - Not yet active.
			
			first = $(this).find("title").eq(0);
			
			$("#slideshow").css("background","black url("+ first +") no-repeat");
			
		 });
	    });

Open in new window

0
Comment
Question by:dwaynecharrington
  • 4
  • 2
6 Comments
 
LVL 16

Accepted Solution

by:
sh0e earned 50 total points
ID: 22847956

fourthitem = $('item:eq(3)',xml);
 
first = $(this).find("title:eq(0)");

Open in new window

0
 
LVL 6

Author Comment

by:dwaynecharrington
ID: 22848682
Hey,

The above solution in theory should be working after reading the jQuery documentation for myself relating to the eq selector. For some reason, the solution didn't work.

When I try rendering the data, it shows [object Object]. But it won't show the actual value of the first element, unless I'm doing it wrong?

Sorry if I seem a bit level headed, jQuery is something I have always neglected to learn properly due to constant time constraints.
0
 
LVL 6

Author Comment

by:dwaynecharrington
ID: 22849005
I also still need to know how to count how many occurances of <item> there is as well in the XML file.
Each <item></item> is a new blog name. I want to know how many blogs their is in the XML file (<item></item>). Not to mention be able to target each element and retrieve it's information separately by addressing it's number by the order it's in.
Obviously the first result is zero and out of four results the last one would obviously be number three.
Sorry if my first question wasn't clear enough for anyone to read. I sometimes find it hard to put thoughts into words. Hopefully I've clarified what I want to achieve now by re-explaining what I want to do.
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 6

Author Comment

by:dwaynecharrington
ID: 22849873
Okay,

I've worked out how to count all of the elements in the XML file.

I've also gotten it to retrieve the title from the XML file. I am having a problem where I can't seem to retrieve any other information from the XML file though. For example, trying to return the value from  returns [Object object].

I've attached updated code:
	<script type="text/javascript">
	$(document).ready(function() 
	{
		getImage('1');
	});
	
	function getCount(xml,nodes) 
	{
        var response = {};
        for (var node in nodes) 
		{
            response[node] = $(nodes[node],xml).length;
        }
        return response;
    }
	
	function getImage(imgnumber)
	{
		// Sexy Ajax ;)
		
		// Open the XML file
		$.get("xml/directory.xml",{},function(xml) 
		{
		 // Return each item found in the XML file with a beginning attribute titled "item"
		 $("item",xml).each(function(i) 
		 {
			/* Variables */
			_title       = $(this).find("title").text();       				  // Item title			
			_image       = $(this).find("image").text();       				  // Image title
			_rssurl      = $(this).find("rssurl").text();      				  // Rss url
			_blogurl     = $(this).find("blogurl").text(); 	   				  // Blog url
			_contributor = $(this).find("contributor").text(); 				  // Contributor Name
			_contributorimg = $(this).find("contributor").attr("imageurl");   // Contributor Image Location (url)
			_contributorpro = $(this).find("contributor").attr("profileurl"); // Controbutor Profile Location (url) - Not yet active.
			
			var count     = getCount(xml,{"item":"item"});
						
			switch(imgnumber)
			{
				case "1":
					_title   = $(i).find("title:eq(1)").text();
					_image   = $("image:eq(1)",xml);
					
					alert(_image);
					
					$("#slideshow").css("background","#000 url("+ _image +") no-repeat");
				break;
				
				default: alert("Ahhhh");
			}
			
		 });
	    });
		
	}
	</script>

Open in new window

0
 
LVL 16

Expert Comment

by:sh0e
ID: 22850622
That's a jQuery wrapped object.  If you want to view the actual object, you need to use get() or text() or html().
If you want an easy jQuery way to count number of objects found, just use length.
$('item',xml).length
$('image:eq(1)').text()
$('image:eq(1)').html()
$('image:eq(1)').get()

Open in new window

0
 
LVL 6

Author Closing Comment

by:dwaynecharrington
ID: 31511955
Thank you for the solution. I realised that you can't have an element called  in the XML file. Upon renamin the image element to imageurl, it worked.

It's now running perfectly. Thank you for your patience and help sh0e.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
$q.all is slower or not  in  Angularjs 2 22
jquery tab header text 1 23
Running a javascript project in WebStorm 2 28
ajax wont trigger twice without a page refresh 7 14
What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question