Jquery Parse XML [英] Jquery Parse XML
本文介绍了Jquery Parse XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用JQuery阅读以下XML。 Jquery应该读取XML并在HTML中显示以下内容,以下所有内容都应该链接
I want to read the following XML using JQuery. The Jquery should read the XML and display the following in HTML, all the following should be linked
News
Articles
---Destinations
---Epics
Tuesday Night Bouldering
我的XML如下所示......
My XML Looks like below...
<category>
<catId>96</catId>
<title>News</title>
</category>
<category>
<catId>97</catId><title>Articles</title>
<category>
<catId>101</catId>
<title>Destinations</title>
</category>
<category>
<catId>102</catId>
<title>Epics</title>
</category>
</category>
<category>
<catId>129</catId>
<title>Tuesday Night Bouldering</title>
</category>
推荐答案
你可以递归地执行此操作。
You can do this recursively.
但你需要让你的xml有一个根节点。
But you need to make your xml have a root node.
这里是你的规格函数(它是核心jQuery,所以我假设移动版本可以应付它)
here is a function for your specs (it is core jQuery so I assume the mobile version can cope with it)
function CategoryToUl(xml){
var categories = xml.children('category');
if (categories.length > 0)
{
var ul = $('<ul/>');
categories.each(function(){
var $this = $(this);
var li = $('<li/>');
var a = $('<a/>',{
text: $this.children('title').text(),
href: '#' + $this.children('catId').text()
});
li.append(a);
li.append( CategoryToUl( $this ) );
ul.append(li);
});
return ul;
}
return null;
}
以下是如何调用它
$.ajax({
url:'path-to.xml',
dataType: 'xml',
success: function(data){
var xml = $(data);
$('#container').append( CategoryToUl(xml.children()) );
}
});
演示 http://www.jsfiddle.net/gaby/UC2dM/1/
它会创建一个这样的结构
It creates a structure like this
<ul>
<li><a href="#96">News</a></li>
<li><a href="#97">Articles</a>
<ul>
<li><a href="#101">Destinations</a></li>
<li><a href="#102">Epics</a></li>
</ul></li>
<li><a href="#129">Tuesday Night Bouldering</a></li>
</ul>
这篇关于Jquery Parse XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文