Parse XML to UL

2020-07-18 09:44发布

问题:

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>

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> 

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:

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

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.

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.

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

I have decided to reply on a PHP solution instead of Javascript. I am using this PHP script: http://www.freesitemapgenerator.com/xml2html.html

回答1:

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>