从jquery中具有相同节点名的子XML节点获取值

时间:2013-04-22 10:49:18

标签: jquery html xml xml-parsing

我在XML下面

<Root>
<field/>
<field/>
<field>
    <label>
        Have you invested before
    </label>
    <value>
        No
    </value>
    <label>
        Are you looking to Invest in the next 6 months
    </label>
    <value>
        Maybe
    </value>
</field>
<field>
    <label>
        What Investments are you interested in
    </label>
    <value>
        Carbon Credits, Green Investments
    </value>
</field>
<field>
    <label>
        How much are you looking to invest
    </label>
    <value>
        £250,000+
    </value>
</field>

从此我需要将其呈现为HTML,如下所示。

Have you invested before: No
Are you looking to invest in the next 6 months: Maybe
What investments are you interested in: Carbon Credits, Green Investments
How much are you looking to invest: £250,000+

目前它的输出是:

:
:     
Have you invested beforeAre you looking to Invest in the next 6 months: YesMaybe
What Investments are you interested in:  Carbon Credits, Green Investments
How much are you looking to invest:    £250,000+

我正在jquery下方使用,但它没有产生我期待的输出。

$(data).find('field').each(function (index, element) {
        debugger;
        //if (field.find('label').length > 0) {
        var field = $(element)
        if (field.find('label').length > 1) {

            var confirmationNumbers = $(field).find("label").map(function () {
                //debugger;
                list.append('<dt>' + label + ': </dt>').append('<dd>' + value + '</dd>');
                return $(this).text();
            });                
            //var label = field.find('label').text()
            //var value = field.find('value').text()
            //list.append('<dt>' + label + ': </dt>').append('<dd>' + value + '</dd>');
        }
        else {
            var label = field.find('label').text()
            var value = field.find('value').text()
            list.append('<dt>' + label + ': </dt>').append('<dd>' + value + '</dd>');
        }
        //}            
    });

我做错了什么..

1 个答案:

答案 0 :(得分:2)

尝试

$(data).find('field label').each(function(){
    var $this = $(this);
    list.append('<dt>' + $this.text() + ': </dt>').append('<dd>' + $this.text().val() + '</dd>');
})

试试这个IE

$(data).find('field label').each(function() {
    var $this = $(this);

    list.append('<div><span>' + $this.text() + '</span><span>'
            + $this.text().val() + '</span></div>');
})