gpt4 book ai didi

javascript - 将 XML 解析为 UL

转载 作者:数据小太阳 更新时间:2023-10-29 02:13:17 26 4
gpt4 key购买 nike

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

在研究了几个小时之后,我决定在正确的方向上我真的需要一些帮助。

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

<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,如下所示:

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 模板上的方式设置所有内容,而是我只专注于让它具有正确的级别:

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

它获取第一个 [0] 元素,www.example.com 这是级别 1,所以它检查是否有 ul[id=1],如果没有然后运行 ​​create_ul 并将其附加到 #content。现在将 li 附加到它刚刚创建的 ul ..级别 1 是“特殊的”,因为它必须首先创建,这就是为什么我有很多 if level==1 在代码中。

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

这种方法根本不适合我,如果说第 8 级具有相同的 id 和第 4 级的某些东西,它也会搞砸。我只需要一个关于如何处理这个问题的新想法。

这是我目前的功能,但我确定我应该放弃大部分代码:

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 被处理为:

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

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

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

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

关于javascript - 将 XML 解析为 UL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5127554/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com