Solved

Counting Elements In XML File With Jquery

Posted on 2008-10-30
6
4,956 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Requirements JQuery 1.6+ HTML CSS Introduction This article was inspired by an EE question (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28372511.html) on how to make a page show some balloons animate up a page…
Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
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…

895 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now