2

I've got a set of data, which are names of places and their location which are saved in an XML file as follows:

<row>
<cell>name</cell>
<cell>location</cell>
</row>

The data was extracted from a spreadsheet and then saved out into XML format. Now in the XML file there are thousands of rows, in this first instance we're looking at 5k+. Is it possible for me to search through this XML file using JavaScript, based on user input and then display this output on an HTML page? I also have to support IE6 (this is a BIG issue)

I'm a total noob with regards to XML but can do a bit of JavaScript and JQuery! Is there an easier way to do this? I don't have the option of using a server side language nor can I use a database (weak I know).

Thanks in advance.

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
zik
  • 3,035
  • 10
  • 41
  • 62

1 Answers1

3

If you have the XML as a string then you should be able to wrap it into a jQuery object like so:

var $myXML = $(myXMLString);

Now you can use the jQuery methods for traversal and searching. For example, search for 'smith' in your cells:

var $matches = $myXML.find("cell:contains('smith')"); //'smith' being your user input

Your XML doesn't appear to have any metadata, so we can't limit the search to a particular field. If your cells had a 'fieldname' for example:

<row>
<cell fieldname='name'>name</cell>
<cell fieldname='location'>location</cell>
</row>

then you could use this:

var $matches = $myXML.find("cell[fieldname='name']:contains(smith)");

See an example at this JSFiddle

EDIT

I've made this a little more sophisticated:

var $myXML = $(myXMLString);

var $rowMatches = $myXML.filter(function(){
    var $cellMatches = $(this).find("cell:contains('smith')");
    return $cellMatches.length > 0; 
});

alert($rowMatches.length);

(Also at this JSFiddle)

Now in your $rowMatches you will have the rows that match your query. The filter function contains a filter for your name. You can try turning this into an array using the $.makeArray() function, or you could iterate over the collection using the .each() function on the collection.

Either way, you should be able to access the other fields in the row.

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • Ok great thanks. But if I were to add in the "fieldnames" or something similar using an editor then I would be able to search on a field? Am I then able to return both fields based on user input? – zik Jul 11 '11 at 12:55
  • I've modified the above sample to cater for you requirement (hopefully). See 'EDIT' – James Wiseman Jul 11 '11 at 13:42
  • Awesome and awesome. Thank you so much. Gonna have a play around with this! – zik Jul 11 '11 at 14:22