2

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

3
  • 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 Commented Sep 7, 2012 at 7:11
  • Post your xml file's code (not the image) and other codes that you have tried . Commented Sep 7, 2012 at 7:15
  • This sound like: write the code for me. And somebody actually did it, you're lucky... Commented Sep 7, 2012 at 8:16

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.