0

我有如下的 xml 字符串。

<Parent>
<child1></child1>
<child2>xxxxxxx</child2>
<child3></child3>
<child4></child4>
</Parent>

我想将此字符串转换为 javascript 中的列表对象。帮帮我,我是 JS 新手。

4

1 回答 1

-1
var data = $.parseXML("<root>  <field>      <label>Have you invested before</label>      <value>No</value>  </field>  <field>      <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>£50,000 -  £100,000</value>  </field></root>")

// query the document to get the list element an store it for later use
var list = $('dl');
// data is a xml document now, so we query it...
$(data)
// and search for all <field> elements
.find('field')
// now we can play with each <field>
.each(function(index, element) {
    // as example we query & store the field
    var field = $(element)
    // get the values we want
    var label = field.find('label').text()
    var value = field.find('value').text()
    // and append some html in the <dl> element we stored previously
    list
        .append('<dt>' + label + ': </dt>')
        .append('<dd>' + value + '</dd>');
});

这是 jsfiddle 中的示例。

http://jsfiddle.net/ecQQn/

于 2013-09-24T11:20:17.993 回答