Please note that this is a particular solution and will only work for the specific layout of code that you provided:
I created a parser in jQuery that receives HTML markup in a textarea and converts it into the format that you are using:
$(function(){
$("button").click(function(){
//Read in HTML
$("#parser").html($("textarea").val());
//Parse
var categories = $("#parser > ul").find("li h3 a");
$(categories).find("span").remove();
//Output result
var output = "<ul>\n";
for(var i = 0; i < categories.length; i++)
{
//Get subcategories for this category
var subCategories = $($(categories[i])).closest("h3").siblings("div").find("ul li a");
//Add markup to output
output += "\t<li>" + minimize($($(categories[i])).html()) + "\n\t\t<ul>\n";
for(var j = 0; j < subCategories.length; j++)
{
output += "\t\t\t<li>"+$($(subCategories[j])).html() + "</li>\n"
}
output += "\t\t</ul>\n\t</li>\n</ul>\n"
}
$("#result").html(output);
});
});
//Removes all white-space characters from the string.
function minimize(str)
{
return str.replace(/\s{2,}/g, '');
}
JSFiddle
It was a lot of work and is very customized. As I said earlier, if you look at the different selectors that are used here, this code is very tailored to this specific code layout.
Example:
var categories = $("#parser > ul").find("li h3 a");
This looks for a ul element just below parser that contains <a>s
inside of <h3>s
inside of <li>s
to find the categories and then later uses
$($(categories[i])).closest("h3").siblings("div").find("ul li a");
which looks for an <h3>
above the category <a>
that has a sibling <div>
with children <ul><li><a></a></li></ul>
So if the format is not this:
<ul>
<li>
<h3>
<a>Category</a>
</h3>
<div>
<ul>
<li>
<a>Subcategory</a>
</li>
</ul>
</div>
</li>
</ul>
It will not work.