Xml To Javascript Array With Jquery
I am new to XML and AJAX and am only a newcomer to Javascript and jQuery. Among other job duties I design our website. A deadline is very near, and the only way I can think of to d
Solution 1:
Using jQuery, $.ajax()
your XML file, and on success pass retrieved data with each
, like:
var tmpSubject, tmpDate, tmpThumb;
$.ajax({
url: '/your_file.xml',
type: 'GET',
dataType: 'xml',
success: function(returnedXMLResponse){
$('item', returnedXMLResponse).each(function(){
tmpSubject = $('subject', this).text();
tmpDate = $('date', this).text();
tmpThumb = $('thumb', this).text();
//Here you can do anything you want with those temporary//variables, e.g. put them in some place in your html document//or store them in an associative array
})
}
});
Solution 2:
I wrote this.. pretty simple way to take a welformed XML response/string and parse it with jquery and then convert to array.
var response = '<?xml version="1.0" encoding="UTF-8"?><root><node1>something</node1></root>'var xmlDoc = $.parseXML( response );
var myArray = getXMLToArray(xmlDoc);
alert(myArray['root']['node1']);
//Pop up window displaying the text "something"functiongetXMLToArray(xmlDoc){
var thisArray = newArray();
//Check XML docif($(xmlDoc).children().length > 0){
//Foreach Node found
$(xmlDoc).children().each(function(){
if($(xmlDoc).find(this.nodeName).children().length > 0){
//If it has children recursively get the inner arrayvarNextNode = $(xmlDoc).find(this.nodeName);
thisArray[this.nodeName] = getXMLToArray(NextNode);
} else {
//If not then store the next value to the current array
thisArray[this.nodeName] = $(xmlDoc).find(this.nodeName).text();
}
});
}
return thisArray;
}
Hope this helps!!
Solution 3:
If you are using jQuery then parseXML will suck an entire xml doc into a usable data structure.
Solution 4:
I added to your script Troublesum
Baca Juga
functiongetXMLToArray(xmlDoc){
var thisArray = newArray();
//Check XML docif($(xmlDoc).children().length > 0){
//Foreach Node found
$(xmlDoc).children().each(function(){
if($(xmlDoc).find(this.nodeName).children().length > 0){
//If it has children recursively get the inner arrayvarNextNode = $(xmlDoc).find(this.nodeName);
thisArray[this.nodeName] = getXMLToArray(NextNode);
} else {
//If not then store the next value to the current array
thisArray[this.nodeName] = [];
$(xmlDoc).children(this.nodeName).each(function(){
thisArray[this.nodeName].push($(this).text());
});
}
});
}
return thisArray;
}
It now also supports many children with same name in XML. f.e
XML being
<countries><NL><borders><country>Germany</country><country>Belgium</country>
countries.NL.borders[1] will give Germany.
Post a Comment for "Xml To Javascript Array With Jquery"