Jquery Parse Xml
I want to read the following XML using JQuery. The Jquery should read the XML and display the following in HTML, all the following should be linked News Articles ---Destination
Solution 1:
You can do this recursively.
But you need to make your xml have a root node.
here is a function for your specs (it is core jQuery so I assume the mobile version can cope with it)
function CategoryToUl(xml){
var categories = xml.children('category');
if (categories.length > 0)
{
var ul = $('<ul/>');
categories.each(function(){
var $this = $(this);
var li = $('<li/>');
var a = $('<a/>',{
text: $this.children('title').text(),
href: '#' + $this.children('catId').text()
});
li.append(a);
li.append( CategoryToUl( $this ) );
ul.append(li);
});
return ul;
}
returnnull;
}
and here is how to call it
$.ajax({
url:'path-to.xml',
dataType: 'xml',
success: function(data){
var xml = $(data);
$('#container').append( CategoryToUl(xml.children()) );
}
});
demo athttp://www.jsfiddle.net/gaby/UC2dM/1/
It creates a structure like this
<ul><li><ahref="#96">News</a></li><li><ahref="#97">Articles</a><ul><li><ahref="#101">Destinations</a></li><li><ahref="#102">Epics</a></li></ul></li><li><ahref="#129">Tuesday Night Bouldering</a></li></ul>
Solution 2:
jQuery.ajax({
type: "GET",
url: 'your_xml.xml', //edit this to be the path of your filedataType: ($.browser.msie) ? "text/xml" : "xml",
success: function(xml) {
var xml2 = load_xml(xml);
var i=0;
$(xml2).find('category').each(function(){
$(xml2).find('catID').each(function(){
//output of catID will be $(this).text()alert($(this).text())
});
$(xml2).find('title').each(function(){
//output of title will be $(this).text()alert($(this).text())
});
});
}
});
and the load XML function:
function load_xml(msg) {
if ( typeof msg == 'string') {
if (window.DOMParser)//Firefox
{
parser=new DOMParser();
data=parser.parseFromString(text,"text/xml");
}else{ // Internet Explorerdata=new ActiveXObject("Microsoft.XMLDOM");
data.async="false";
data.loadXML(msg);
}
} else {
data = msg;
}
returndata;
}
sorry, I feel I should explain - this load_xml()
function will work crossbrowser (IE, FireFox, Chrome, Safari etc).
Solution 3:
JQuery gets as easy as this:
var xml = your xml...
JQuery(xml).find('category').each(function(){
JQuery(xml).find('catID').each(function(){
alert($(this).text())
});
});
Solution 4:
This is the correct AJAX
jQuery.ajax({
type: "GET",
url: 'your_xml.xml', //edit this to be the path of your filedataType: ($.browser.msie) ? "text/xml" : "xml",
success: function(xml) {
var xml2 = load_xml(xml);
var i=0;
$(xml2).find('category').each(function(){
var category = $(this);
category.find('catID').each(function(){
//output of catID will be $(this).text()alert($(this).text())
});
category.find('title').each(function(){
//output of title will be $(this).text()alert($(this).text())
});
});
}
});
Post a Comment for "Jquery Parse Xml"