I parse XML ( http://gyazo.com/fe38f0eb89a1f1f88927f676f304cc1c ) to JSON with a plugin. I want it to loop through all categories and for each loop cycle repeat the process for child categories and props, it should be doing this infinitely so with a loop.
I have looked into recursive functions and it's what I am attempting but it's not working for me cause the console.log always says that it's undefined as soon as I try $.each to get the child elements.
JQuery
function ParseData(v) {
var caption = v.caption;
console.log('Category ' + caption + ' parsed.');
if (v.prop != undefined) {
console.log('Prop(s) found, parsing....');
$.each(v.prop, function(key, value) {
ParseData(v.prop);
});
}
else if (v.cat != undefined) {
console.log('Child(s) found, parsing....');
$.each(v.cat, function(key, value) {
ParseData(v.cat);
});
}
}
function loadProps() {
//variables
var pb = $('div#prop_browser');
//parse prop categories
console.log('Parsing Categories....');
$.get("prop-cat.xml", function(xml) {
var data = $.xml2json(xml);
$.each(data, function(key, value) {
$.each(value, function(key, value) {
ParseData(value);
});
});
});
}
I have literally spent hours and hours of googling and coding but I cannot figure this out and I doubt that it is my logic....
Please help me!
Sample JSON (used JSON.stringify instead of ParseData): First JSON string has two categories, one prop. Second JSON string has one category and one prop.
{"cat":[{"id":"0","caption":"Dog 1","img":""},{"id":"0","caption":"Dog 9","img":""}],"prop":{"caption":"Prop 1","img":""},"id":"0","caption":"Cat 1","img":""}
{"cat":{"id":"0","caption":"Dog 1","img":""},"prop":{"caption":"Prop 2","img":""},"id":"0","caption":"Cat 2","img":""}
@charlietfl's JSFiddle, doesnt work wth is going on!
function processData() {
$(pb).append('<div class="prop_category">' + $(this).attr('caption'));
if ($(this).children().length > 0) {
$(this).children().each(processData);
} else {
$(pb).append('</div>');
}
}
function loadProps() {
//variables
pb = $('#prop_browser');
$.get("prop-cat.xml", function(xml) {
$(xml).children().each(processData);
});
}