I am working on a project that requires me to parse an XML tree where the XML is not so great. I need to define a UL structure from the XML but the issue is that all the nodes are the same name with different attributes. I am using jQuery ajax function to call this XML file and return it on success. Here is my conundrum:
> <class name="Juice">
> <class name="OJ">
> <class name="Low Sugar" />
> <class name="Some Pulp" />
> </class>
> <class name="Apple" />
> <class name="Grape" />
> </class>
As you can see the node names make it hard to transpose this to a uniformed list. I am trying to get this to recurse and look like this:
<ul>
<li>Juice
<ul>
<li>OJ
<ul>
<li>Low Sugar</li>
<li>Some Pulp</li>
</ul>
</li>
<li>Apple</li>
<li>Grape</li>
</ul>
</li>
</ul>
my ajax call:
$.ajax({
type: "GET",
url: "nav.xml",
dataType: "xml",
success: function (xml) {
xmlParser(xml);
}
});
my xmlParser function:
function xmlParser(xml) {
$(xml).find("class class").each(function () {
var cname = $(this).attr("name");
if ($(this).children.length > 0) {
$("#nav .categories").append("<li id='" + cname + "'><a href='#'>" + cname + "</a></li>");
$(xml).find("[name='" + cname + "']").children().each(function () {
var cname1 = $(this).attr("name");
$("#" + cname).append("<ul></ul>");
$("#" + cname + " ul").append("<li id='" + cname1 + "'><a href='#'>" + cname1 + "</a></li>");
});
} else {
$("#nav .categories").append("<li id='" + cname + "'><a href='#'>" + cname + "</a></li>");
}
});
}
My HTML on the page where I want to append the unordered list:
<ul id="nav" class="categories"></ul>
This ends up duplicating some code and is not recursive, I would like to get something where I can recall the parseXml function and pass some argument where the elements are not duplicated in the tree. I would rather trash this function and start over with something cleaner and neater.
Are there any jQuery plugins that do this already. I have checked this site and Google but nothing I am looking for works with this bad XML. All others I found use a well formed XML structure.
Thanks in advance.