将XML解析为UL [英] Parse XML to UL

查看:83
本文介绍了将XML解析为UL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JQuery解析sitemap.xml,使其看起来像这样的HTML: http://astuteo .com/slickmap/demo/

I am trying to use JQuery to parse a sitemap.xml to look like this HTML: http://astuteo.com/slickmap/demo/

研究了几个小时后,我认为我确实需要一些正确方向的帮助.

After working on it for a few hours I decided I really need some help in the right direction.

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

the main template it has is this, where each indent is a different directory level:

<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>

我正在使用如下所示的google sitemap.xml:

I am using a google sitemap.xml which looks like this:

http://meyers.ipalaces.org/sitemap_000.xml

<url> 
  <loc>http://meyers.ipalaces.org/</loc> 
  <lastmod>2011-02-26T09:32:18Z</lastmod> 
  <changefreq>hourly</changefreq> 
  <priority>0.4</priority> 
</url> 
<url> 
  <loc>http://meyers.ipalaces.org/meyers/photos/Explorer</loc> 
  <lastmod>2011-02-26T09:31:33Z</lastmod> 
  <changefreq>hourly</changefreq> 
  <priority>0.2</priority> 
</url> 

我想出的方法可以避免在CSS模板上准确设置所有内容,而我只是专注于使它具有正确的级别:

The method I came up with avoids setting everything exactly how it is on the css template, but instead I just focused on getting it to have the correct levels:

它所做的是将URL级别遍历每个级别,以尝试根据上一个级别创建列表.因此,以示例www.example.com/brand/model/product/:

What it does is takes the level of a URL goes through each level trying to create the list based on the previous level. So with the example www.example.com/brand/model/product/:

它得到第一个[0]元素,www.example.com是级别1,因此它检查是否有ul[id=1],如果没有,则运行create_ul并将其附加到#content.现在将li附加到它刚制成的ul上..level1是特殊"的,因为必须首先创建它,这就是为什么我在代码中有很多if level==1的原因.

it gets the first [0] element, www.example.com this is level 1 so it checks is there a ul[id=1], if not then run create_ul and append it to #content. Now attach a li to the ul it just made..level 1 is "special" because it has to be created first, thats why I have a lot of if level==1 in the code.

对于下一个元素[1],它得到brand级别2.这次它检查 是否存在li[id=www.example.com] ul[id=2](如果存在),它将创建一个li[id=www.example.com] ul[id=2],然后将li附加到ul.

For the next element [1] it gets brand which is level 2. This time it checks is there a li[id=www.example.com] ul[id=2] if there exist, it will create one and then attach a li to the ul.

这个方法对我来说根本行不通,如果说第8级具有相同的ID和第4级中的值,它也会弄乱我.我只需要一个关于如何实现此方法的新思路即可.

This method isn't working out for me at all, it also messes up if say level 8 has the same id and something from level 4. I just need a new idea on how to approach this.

到目前为止,这是我的功能,但是我确定我应该只删除大部分代码:

Here is my functions as of now, but im sure I should just scrap most of the code:

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);
            }
        });
    });
}


我决定回答一个PHP解决方案,而不是Javascript.我正在使用以下PHP脚本: http://www.freesitemapgenerator.com/xml2html.html

推荐答案

这是我的尝试.

基本上,它使用数组来存储所有url的.
例如,URL mytest.url.com/sub1/othersub2.html的处理方式为:

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'];

这是可能的,因为javascript允许您使用字符串对数组进行索引.

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

完整代码(只需替换您的parseXml函数并在带有Firebug的chrome或firefox上对其进行测试):

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>

这篇关于将XML解析为UL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆