Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将XML解析为UL_Javascript_Jquery_Xml_Parsing_Sitemap - Fatal编程技术网

Javascript 将XML解析为UL

Javascript 将XML解析为UL,javascript,jquery,xml,parsing,sitemap,Javascript,Jquery,Xml,Parsing,Sitemap,我正在尝试使用JQuery解析sitemap.xml,使其看起来像以下HTML: 经过几个小时的努力,我决定在正确的方向上我真的需要一些帮助 它的主要模板是这样的,其中每个缩进都是不同的目录级别: <ul id="primaryNav" class="col4"> <li id="home"><a href="http://sitetitle.com">Home</a></li> <li><a href

我正在尝试使用JQuery解析sitemap.xml,使其看起来像以下HTML:

经过几个小时的努力,我决定在正确的方向上我真的需要一些帮助

它的主要模板是这样的,其中每个缩进都是不同的目录级别:

<ul id="primaryNav" class="col4">
    <li id="home"><a href="http://sitetitle.com">Home</a></li>
    <li><a href="/services">Services</a>
        <ul>
            <li><a href="/services/design">Graphic Design</a></li>
            <li><a href="/services/development">Web Development</a></li>
            <li><a href="/services/marketing">Internet Marketing</a>
                <ul>
                    <li><a href="/social-media">Social Media</a></li>
                    <li><a href="/optimization">Search Optimization</a></li>
                    <li><a href="/adwords">Google AdWords</a></li>
                </ul>
            </li>
            <li><a href="/services/copywriting">Copywriting</a></li>
            <li><a href="/services/photography">Photography</a></li>
        </ul>
    </li>
</ul>

我决定用PHP解决方案而不是Javascript来回复。我正在使用这个PHP脚本:

这是我的尝试

基本上,它使用一个数组来存储所有URL的片段。
例如,url
mytest.url.com/sub1/othersub2.html
被处理为:

var map = ['mytest.url.com']['sub1']['othersub2.html'];
这是可能的,因为javascript允许您使用字符串索引数组

完整代码(只需替换您的
parseXml
函数,并使用firebug在chrome或firefox上进行测试):


函数解析xml(xml){
//这里我们将存储表示URL的嵌套数组
var-map=[];
$(xml).find(“loc”).each(函数(){
//由于提供了错误的URL,某些字符串被清除
//(结束斜杠或双斜杠)
var url=this.textContent.replace('http://','').replace('//',''),
endingislash=(url.substr(url.length-1,1)='/'),
cleanedUrl=url.substr(0,url.length-(endingSlash?1:0)),
splittedUrl=cleanedUrl.split('/'),//按斜杠拆分
currentArrayLevel=map;//我们从基本url开始
对于(var i=0;i
有人可以向我解释为什么没有将代码正确地突出显示为“javascript”?编辑:好的,通过添加
标记来欺骗它。
function create_ul(level, id, prev_id) {
        var ul = $('<ul/>',{
            id: level
        });

        if(level==1) {
            $('#content').append(ul);
        } else {
            $('ul[id='+(level-1)+'] li[id='+prev_id+']').append(ul);
        }
}



function create_li(level, id, prev_id){
    if (level ==1){
        if ($('ul[id='+level+']').length == 0) {
            create_ul(level, id, prev_id);
        } else if ($('ul[id='+level+'] li[id='+id+']').length > 0) {
            return;
        }

        var li = $('<li/>',{
            id: id
        });

        var a = $('<a/>',{
            text:   level + " - " + id,
            href:  "nothing yet"
        });

        $('ul[id='+level+']').append(li);
        return;
    } 
    // If there is no UL for the LI, create it
    if ($('li[id='+prev_id+'] ul[id='+level+']').length == 0) {
        create_ul(level, id, prev_id);
    } else if ($('ul[id='+level+'] li[id='+id+']').length > 0) {
        return;
    }

    var li = $('<li/>',{
        id: id
    });


        var a = $('<a/>',{
            text:   level + " - " + id,
            href:  "nothing yet"
        });

    li.append(a);


    $('li[id='+prev_id+'] ul[id='+level+']').append(li);
}

$.ajax({  
    type: "GET",  
    url: "/sitemap_000.xml",  
    dataType: "xml",  
    success: parseXml  
});  

function parseXml(xml) {   
    URLS = new Array(new Array(), new Array(), new Array());
    $(xml).find("loc").each(function(){
        var url = $(this).text();
        URLS[1].push(url);

        url = url.replace("http://", "")
        var url_array = url.split("/");

        URLS[0].push(url_array);

        var rawLastMod = $(this).parent().find('lastmod').text();  
        var timestamp = rawLastMod.replace(/T.+/g, '');
        var lastMod = formatDate(timestamp);


        URLS[2].push(lastMod);
    });



    $(URLS[0]).each(function(i, url_array){
        $(url_array).each(function(index, fragment){
            var level = index+1;
            var id = fragment;
            if(index!=0) {
                var prev_id = URLS[0][i][index-1];
            } else {
                var prev_id = null;
            }

            if(id != "") {                                          
                create_li(level, id, prev_id);
            }
        });
    });
}
var map = ['mytest.url.com']['sub1']['othersub2.html'];
<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>