我需要能够搜索XML文件并找到符合用户输入条件的所有结果。 XML文件中有大约1000条记录。有五个字段:"课程名称," "开始日期," "完成"," CompleteDate"和"代码。"找到结果后,将它们放入HTML表中。
XML文件:
<?xml version="1.0" encoding="utf-8"?>
<lessons>
<lesson>
<code>4889</code>
<lessonname>Lesson 1</lessonname>
<startdate>2016-03-03 00:59:43</startdate>
<complete>1</complete>
<completedate>2016-03-03 01:35:19</completedate>
</lesson>
<lesson>
<code>4889</code>
<lessonname>Lesson 2</lessonname>
<startdate>2016-03-18 00:30:00</startdate>
<complete>1</complete>
<completedate>2016-03-03 01:35:19</completedate>
</lesson>
</lessons>
此时,我可以从XML文件中获取所有记录并将它们放入表中。但是,我想将结果限制为仅匹配用户键入文本框的结果。我不确定如何过滤结果。这是我尝试过的:
jQuery代码
function getXmlDataFromAPI() {
$.ajax({
type: "GET",
url: "pathToFile",
dataType: "xml",
success: function (xml) {
var totalRowsReturned = xml.childNodes[0].childElementCount;
var lessonName = document.getElementById("lessonNameBox").value;
var startDate = document.getElementById("startDateBox").value;
var code = document.getElementById("codeBox").value;
$(xml).find('lesson').each(function () {
if ($(this).find('lessonname').text() == lessonName) {
var col0 = $(this).find('code').text();
var col1 = $(this).find('startdate').text();
var col2 = $(this).find('lessonname').text();
var col3 = $(this).find('complete').text();
var col4 = $(this).find('completedate').text();
$('<tr></tr>').html('<td>' + col0 + '</td><td>' + col1 + '</td><td>' + col2 + '</td><td>' + col3 + '</td><td>'
+ col4 + '</td>').appendTo('#apiXmlTable');
}
else {
alert("The criteria you entered does not match any of the records on file.");
}
});
//make the table-containing div, clear button, the table, and the total results box visible
$("#apiXmlTable").show();
$("#xmlTableContainer").show();
$("#clearTableBtn").show();
$("#ipt_totalResultsBox").show();
$("#resultsLabel").show();
//set the text for the total results box
document.getElementById("ipt_totalResultsBox").value = totalRowsReturned;
//make the search button invisible
$("#searchBtn").css("display", "none");
},
error: function (xhr, status, error) {
alert("The data could not be retrieved.");
}
});
}
正如您所看到的,这将获取xml文件中的所有数据并将其放入表中。如何根据用户输入过滤结果?另外,我想显示找到的结果总数。我怎样才能做到这一点?