I have the following xml :
<blop></blop>
<yop></yop>
<here>
<thefirst>value1</thefirst开发者_开发百科>
<second>value2</second>
<thiiiiird>3rdValue</thiiiiird>
<here>
I want to do a table like this :
thefirst value1
second value2
thiiiiird value3
I tried :
$(this).find("here").each(function(){
$(this).each(function(){$('#stuff').append("<br />"+$(this).text());});
});
but it display all values at once. How can i create my array? Is it possible in javascript and or Jquery?
You could try looping through the children of here
. The way you have it set up now your loops are not gonna get it work.
This might give you some direction...
Creating an array
var hereArr = [];
$(this).find("here").each(function(index, el){
$(el).children().each(function(index2, el2){
hereArr[index][el2.nodeName] = $(el2).text();
});
});
In theory (completely untested, i manually parse xml... so i'm not familiar with jQuery+xml) this would create a multi-dimensional array for you which would looks something like...
//first "here"
[0]['thefirst'] = value1;
[0]['second'] = value2;
[0]['thiiiiird'] = value3;
Output to a table
var htmlStr = "";
$(this).find("here").each(function(index, el){
$(el).children().each(function(index2, el2){
htmlStr += "<tr>";
htmlStr += " <td>" + el2.nodeName + "</td>";
htmlStr += " <td>" + $(el2).text() + "</td>";
htmlStr += "</tr>";
});
});
$("table").append( htmlStr );
$(this).find("here").each(function() {
$(this).each(function() {
$('#stuff').append("<br />" + $(this).text())
})
});
Watch the use of ;
(this should probably be a comment but I can't exactly post them yet)
Your XML is not well-formed. your here tag is not properly closed, and this will affect how JQuery processes the response. It may contribute to why you're seeing everything all at once, especially if you're retrieving the response as TEXT instead of as XML.
In Firebug, check the XML tab in the response and you can see that the XML parser complains about an error. The parser also complained because you don't have a documentElement. I wrapped the response in a "result" parent. Here is what your XML should look like:
<?xml version="1.0" encoding="UTF-8"?>
<result>
<blop></blop>
<yop></yop>
<here>
<thefirst>value1</thefirst>
<second>value2</second>
<thiiiiird>3rdValue</thiiiiird>
</here>
</result>
Here is an example AJAX call:
$.ajax({ url: 'xmldoc.xml', dataType: 'xml', success: function(data) {
// note: success is called ONLY if the XML is well-formed.
console.info($(data).find('thefirst').text());
$('table tbody').append('<tr><td>thefirst</td><td>'+$(data).find('thefirst').text()+'</td></tr>');
$('table tbody').append('<tr><td>second</td><td>'+$(data).find('second').text()+'</td></tr>');
$('table tbody').append('<tr><td>thiiiiird</td><td>'+$(data).find('thiiiiird').text()+'</td></tr>');
});
精彩评论