Jquery Parse XML

use*_*950 3 javascript xml jquery jquery-ui

我想使用JQuery阅读以下XML.Jquery应该读取XML并在HTML中显示以下内容,以下所有内容都应该链接

News
Articles 
  ---Destinations
  ---Epics
Tuesday Night Bouldering
Run Code Online (Sandbox Code Playgroud)

我的XML看起来如下......

    <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>
Run Code Online (Sandbox Code Playgroud)

Gab*_*oli 10

你可以递归地做到这一点.

但是你需要让你的xml有一个根节点.

这是你的规范的一个功能(它是核心jQuery,所以我假设移动版本可以应付它)

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;
}
Run Code Online (Sandbox Code Playgroud)

以下是如何调用它

$.ajax({
    url:'path-to.xml',
    dataType: 'xml',
    success: function(data){
        var xml = $(data);
        $('#container').append( CategoryToUl(xml.children()) );
    }
});
Run Code Online (Sandbox Code Playgroud)

演示 http://www.jsfiddle.net/gaby/UC2dM/1/


它创建了这样的结构

<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>
Run Code Online (Sandbox Code Playgroud)