How to create Dynamic Menu using XML & Jquery

10,499

You can try this

XML

<?xml version="1.0" encoding="utf-8" ?>
    <MenuRoot>
        <Menu id="home" text="Home" url="home.aspx"></Menu>
        <Menu id="projects" text="Projects" url="projects.aspx">
            <SubMenu id="sub1" text="Sub One" url="subone.aspx"></SubMenu>
            <SubMenu id="sub2" text="Sub Two" url="subtwo.aspx"></SubMenu>
        </Menu>
    </MenuRoot>

HTML

<div id="menu_wrapper"></div>

JS

$(document).ready(function(){
        $.ajax({
            type: "GET",
            url: "jquery_xml.xml",
            dataType: "xml",
            success: function(xml){
                var ul_main=$("<ul />");
                $(xml).find("Menu").each(function(){
                    if($(this).children().length)
                    {
                        var ulSub=$("<ul />");
                        $(this).children().each(function(){
                            ulSub.append("<li id="+$(this).attr("id")+"><a href="+$(this).attr("url")+">"+$(this).attr("text")+"</a></li>");
                        });
                        var li=$("<li id="+$(this).attr("id")+"><a href="+$(this).attr("url")+">"+$(this).attr("text")+"</a></li>");
                        ul_main.append(li.append(ulSub))
                    }
                    else ul_main.append("<li id="+$(this).attr("id")+"><a href="+$(this).attr("url")+">"+$(this).attr("text")+"</a></li>");
                });
                $("#menu_wrapper").append(ul_main);
            }
        });
});

Output

enter image description here

You just need to style your menu using css.

Share:
10,499

Related videos on Youtube

suman
Author by

suman

Updated on June 04, 2022

Comments

  • suman
    suman about 2 years

    I have an xml as like belowenter image description here

    above is an example of my xml file. Now my requirement is to read the xml file and build a menu using jquery.

    can some one please help me

    • suman
      suman almost 12 years
      we have already done it using asp.net, we are reading the xml file using C# and later binding it with asp:menu control. now we are supposed to implement it with mvc. so, we want to create a menu using jquery by reading the above xml
    • The Alpha
      The Alpha almost 12 years
      Post your xml file's code (not the image) and other codes that you have tried .
    • themarcuz
      themarcuz almost 12 years
      This sound like: write the code for me. And somebody actually did it, you're lucky...
  • suman
    suman almost 12 years
    Thanks for your reply sheikh, i will try this :)