使用 jQuery .each 循环遍历 XML 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7070886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using jQuery .each to loop over XML file
提问by Darin
I have an XML file that is pretty long. Below is the code I am using to retrieve the file and then go through the file using jQuery's .each(), outputting the correct information:
我有一个很长的 XML 文件。下面是我用来检索文件然后使用 jQuery 的 .each() 遍历文件的代码,输出正确的信息:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Table').each(function(index){
var provider = $(this).find('Provider').text();
var channel = $(this).find('FeedCommonName').text();
var hd = $(this).find('FeedIsHD').text();
$('.box ul').append('<li>'+channel+'</li>');
});
}
});
});
The problem I'm having is the code only gives me up to element 31. I added the index variable in to see that, and it is giving me an index from 0 to 30. So is there some limitation that .each() only goes up to an index of 30, and if so, is there another way to go through the XML file? Thanks.
我遇到的问题是代码只给了我元素 31。我添加了索引变量来查看它,它给了我一个从 0 到 30 的索引。那么 .each() 是否有一些限制上升到 30 的索引,如果是这样,是否有另一种方法来浏览 XML 文件?谢谢。
EDIT: Solved, at least for now. There were &'s in the XML file, which was holding up the processing. I guess another reminder to validate your source file first.
编辑:解决了,至少现在是这样。XML 文件中有 & 符号,它阻止了处理。我想再次提醒您首先验证您的源文件。
回答by ShankarSangoli
Try using parseXML
before you find the element
parseXML
在找到元素之前尝试使用
$(document).ready(function(){
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: function(xml) {
$.parseXML(xml).find('Table').each(function(index){
var provider = $(this).find('Provider').text();
var channel = $(this).find('FeedCommonName').text();
var hd = $(this).find('FeedIsHD').text();
$('.box ul').append('<li>'+channel+'</li>');
});
},
error: function() {
$('.box ul').text("Failed to get xml");
}
});
});