使用jquery从xml获取数据

时间:2014-01-29 20:47:51

标签: javascript jquery xml parsing

<?xml version="1.0" encoding="UTF-8"?>
<slider>
    <csliderData1>
        <title>Kung Fu Panda</title>
        <content>In the Valley of Peace, Po the Panda finds himself chosen as the Dragon Warrior despite</content>
        <img>pages/images/slider/a.jpg</img>
    </csliderData1>

    <csliderData2>
        <title>Despicable Me</title>
        <content>Gru is recruited by the Anti-Villain League to help deal with a powerful new super criminal.</content>
        <img>pages/images/slider/b.jpg</img>
    </csliderData2>

    <csliderData3>
        <title>Craigslist Joe</title>
        <content>In a time when America's economy was crumbling and sense of community was in question</content>
        <img>pages/images/slider/c.jpg</img>
    </csliderData3>

    <csliderData4>
        <title>X: Night of Vengeance</title>
        <content>A jaded call-girl. A fledgling hooker. The night from hell.</content>
        <img>pages/images/slider/d.jpg</img>
    </csliderData4>

    <csliderData5>
        <title>Rock of Ages</title>
        <content>A small town girl and a city boy meet on the Sunset Strip, while pursuing their Hollywood dreams</content>
        <img>pages/images/slider/e.jpg</img>
    </csliderData5>
</slider>

大家好,我怎么能用jquery从xml中获取数据? 我想获取这些数据并放入多维数组,如下所示:

var slideShowContent = Array(
    Array('Kung Fu Panda', 'In the Valley of Peace, Po the Panda finds himself chosen as the Dragon Warrior despite', 'pages/images/slider/a.jpg'), 
    Array('Despicable Me', 'Gru is recruited by the Anti-Villain League to help deal with a powerful new super criminal.', 'pages/images/slider/b.jpg'), 
    Array('Craigslist Joe', "In a time when America's economy was crumbling and sense of community was in question", 'pages/images/slider/c.jpg'), 
    Array('X: Night of Vengeance', 'A jaded call-girl. A fledgling hooker. The night from hell.', 'pages/images/slider/d.jpg'), 
    Array('Rock of Ages', 'A small town girl and a city boy meet on the Sunset Strip, while pursuing their Hollywood dreams.', 'pages/images/slider/e.jpg'));

3 个答案:

答案 0 :(得分:0)

试试这个插件: https://github.com/josefvanniekerk/jQuery-xml2json(“一个简单的jQuery插件,可以将XML数据(通常是$ .ajax请求)转换为有效的JSON对象。”)

答案 1 :(得分:0)

这样的东西适用于解析的XML

var slideShowContent = $.map($(xml).find('slider').children(), function(node, i) {
    return [[$('title', node).text(), $('content', node).text(), $('img', node).text()]];
});

FIDDLE

答案 2 :(得分:0)

var xml_data = '[xml_data_here]',
    $slider = $( $.parseXML(xml_data) ).find('slider'),
    slider_data = [];

$slider.children().each(function() {
    var slide = [];
    $(this).children().each(function() {
        slide.push( $(this).text() );
    });

    slider_data.push( slide );
});