使用JavaScript从XML文件搜索和输出数据
我有一组数据,这些数据是地点名称及其位置,并保存在XML文件中,如下所示:
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>
从电子表格中提取数据,然后将其保存为XML格式.现在在XML文件中有成千上万的行,在第一个实例中,我们看的是5k +.我是否可以根据用户输入使用JavaScript搜索此XML文件,然后在HTML页面上显示此输出?我还必须支持IE6(这是一个大问题)
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)
关于XML我是一个菜鸟,但可以使用JavaScript和JQuery!有没有更简单的方法可以做到这一点?我不能选择使用服务器端语言,也不能使用数据库(我知道很弱).
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).
谢谢.
如果将XML作为字符串,则应该能够将其包装到jQuery对象中,如下所示:
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);
现在,您可以使用jQuery方法进行遍历和搜索.例如,在您的单元格中搜索史密斯":
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
您的XML似乎没有任何元数据,因此我们不能将搜索限制为特定字段.例如,如果您的单元格具有字段名":
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>
然后您可以使用此:
var $matches = $myXML.find("cell[fieldname='name']:contains(smith)");
编辑
我已经做了一些复杂的事情:
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);
(也在此JSFiddle 中)
现在在您的$rowMatches
中,将具有与查询匹配的行. filter
函数包含用于您的姓名的过滤器.您可以尝试使用$.makeArray()
函数将其转换为数组,也可以使用集合上的.each()
函数遍历集合.
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.