Parse XML to UL

◇◆丶佛笑我妖孽 提交于 2019-12-04 09:22:24

This is my try to it.

Basically it uses an array to store all the urls' pieces.
For example, the url mytest.url.com/sub1/othersub2.html is handled as:

var map = ['mytest.url.com']['sub1']['othersub2.html'];

This is possible because javascript allows you to index arrays using strings.

Full code (just replace your parseXml function and test it on chrome or firefox with firebug):

<script type="text/javascript">
function parseXml(xml) {
    //here we will store nested arrays representing the urls
    var map = []; 
    $(xml).find("loc").each(function () {
        //some string cleaning due to bad urls provided
        //(ending slashes or double slashes)
        var url = this.textContent.replace('http://', '').replace('//', ''),
            endingInSlash = (url.substr(url.length - 1, 1) == '/'),
            cleanedUrl = url.substr(0, url.length - (endingInSlash ? 1 : 0)),
            splittedUrl = cleanedUrl.split('/'),  //splitting by slash
            currentArrayLevel = map; //we start from the base url piece

        for (var i = 0; i < splittedUrl.length; i++) {
            var tempUrlPart = splittedUrl[i];
            //in javascript you can index arrays by string too!
            if (currentArrayLevel[tempUrlPart] === undefined) {
                currentArrayLevel[tempUrlPart] = [];
            }
            currentArrayLevel = currentArrayLevel[tempUrlPart];
        }
    });

    var currentUrlPieces = [];  //closure to the recursive function
    (function recursiveUrlBuilder(urlPiecesToParse) {
        //build up a DOM element with the current URL pieces we have available
        console.log('http://' + currentUrlPieces.join('/'));  

        for (var piece in urlPiecesToParse) {
            currentUrlPieces.push(piece);
            //recursive call passing the current piece
            recursiveUrlBuilder(urlPiecesToParse[piece]);  
        }
        //we finished this subdirectory, so we step back by one
        //by removing the last element of the array
        currentUrlPieces.pop();   
    })(map);
}
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!