2013-09-24 41 views
0

我有如下所示的xml字符串。將Xml轉換爲javascript列表

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

我想將此字符串轉換爲JavaScript中的列表對象。幫助我,我是新的JS。

+0

檢查Mozilla的XML解析教程的JavaScript文件https://developer.mozilla.org/en/docs/Parsing_and_serializing_XML,如果你仍然面臨一個問題,請向特定問題 – AurA

回答

-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/