Solved

Counting Elements In XML File With Jquery

Posted on 2008-10-30
6
4,943 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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)
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…

706 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

18 Experts available now in Live!

Get 1:1 Help Now