search and output data from an XML file using JavaScript
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.
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.
精彩评论