JavaScript Recursion to format lists from XML to HTML

前端 未结 1 1440
离开以前
离开以前 2021-01-16 07:00

I have an exercise where it calls upon me to use recursion to output XML data into HTML list tags. Shamefully admitting my shortcomings in mathematics, I would like someone

相关标签:
1条回答
  • 2021-01-16 07:34

    You call your recursive function once with your top level element. Every child element will simply call the same function. When you get to the bottom, you stop, and everything gets passed back up.

    This should get your started (a sample of your xml).

    Demo:

    Output:

    output

    Script:

    document.getElementById( 'parse' ).addEventListener( 'click', function () {
        var xml = '<ddm>'
                    + '<menu0 submenu="true"><name>Welcome</name>'
                        + '<menu1>Home Page</menu1>'
                        + '<menu1>Bulletin</menu1>'
                    + '</menu0>'
                    + '<menu0 submenu="true"><name>Members\' Area</name>'
                        + '<menu1>Constitution &amp; Bylaws</menu1>'
                        + '<menu1 submenu="true"><name>AGM Minutes</name>'
                            + '<menu2>2012</menu2>'
                            + '<menu2>2011</menu2>'
                        + '</menu1>'
                    + '</menu0>'
                    + '<menu0>About</menu0>'
                + '</ddm>',
            xmlDoc = new DOMParser().parseFromString( xml, 'text/xml' ),
            html = nodeMarkup( xmlDoc.documentElement );
        document.getElementById( 'result' ).innerHTML = html;
    } );
    
    function nodeMarkup( node ){
        if( node.childNodes.length ) {
            var list = '', header = '';
            for( var index = 0; index < node.childNodes.length; index++ ) {
                if( node.childNodes[index].tagName == 'name' ) {
                    header = node.childNodes[index].textContent;
                } else {
                    list += nodeMarkup( node.childNodes[index] );
                };
            };
            return node.hasAttribute( 'submenu' ) 
                ? '<li>' + header + '<ul>' + list + '</ul></li>'
                : list;
        } else {
            return '<li>' + node.textContent + '</li>';
        };  
    };
    

    HTML:

    <input type="button" id="parse" value="Parse" />
    <ul id="result"></ul>
    

    CSS:

    #result {
        list-style-type: none;
        margin: 0;
        padding: 0;
    }
    
    0 讨论(0)
提交回复
热议问题