我从远程api收到如下例子的xml数据。谁能告诉我如何获取键名及其相应的键值并打印出来?例如,我想打印所有categoryIcon和类别值。
javascript:
$.get("http://www.someapisite.com/test.php",
{
dataType: "jsonp"
},
function(data,status){
//here i want to print the key names and its corresponding values
}
解析xml:
<?xml version="1.0" encoding="UTF-8"?>
<dict><key>ItemLists</key>
<array><dict><key>id</key>
<string>1</string>
<key>name</key>
<string>fruits</string>
<key>category</key>
<string>US Fruits</string>
<key>categoryIcon</key>
<string>http://www.somsite.com/categories/1.jpg</string>
<key>country</key>
<string>US</string>
</dict>
<dict><key>id</key>
<string>2</string>
<key>name</key>
<string>Vegetable</string>
<key>category</key>
<string>Eu Vegetable</string>
<key>categoryIcon</key>
<string>http://www.somsite.com/categories/2.jpg</string>
<key>country</key>
<string>EU</string>
</dict>
</array>
</dict>
编辑
对于每组dict,我想打印<tr>
就像这样:
var div = "<tr id=\""+i+"\">\n" +
"<td>"+i+"</td>\n" +
"<td><img src=\""+ categoryIcon +"\" height=\"42\" width=\"42\"></td>\n" +
"<td>\n" +
"<a href=\"javascript:doit('id=" + id + "&name=" + name + "&category=" + category + "&categoryIcon=" + categoryIcon + "','"+ country +"')\" onclick=\"selectLink(this);\">" + name + "</a><br> \n" +
"<br></td></tr>\n\n";
$("#myDiv").append(div);
答案 0 :(得分:1)
首先,您需要使用parseXML()
将字符串解析为XML文档,然后您可以在文档中找到您的键/值。您应该在key
标记中找到array
标记,并使用.each()
进行迭代。 key
标记中的string
值也可以使用.next()
来选择它。
var xml = $("#xml").html();
$(xml).find("array key").each(function(){
var key = $(this).text();
var value = $(this).next().text();
console.log(key + "=" + value);
});
var xml = $("#xml").html();
$(xml).find("array key").each(function(){
console.log($(this).text() +"="+ $(this).next().text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="xml">
<dict>
<key>ItemLists</key>
<array>
<dict>
<key>id</key>
<string>1</string>
<key>name</key>
<string>fruits</string>
<key>category</key>
<string>US Fruits</string>
<key>categoryIcon</key>
<string>http://www.somsite.com/categories/1.jpg</string>
<key>country</key>
<string>US</string>
</dict>
<dict>
<key>id</key>
<string>2</string>
<key>name</key>
<string>Vegetable</string>
<key>category</key>
<string>Eu Vegetable</string>
<key>categoryIcon</key>
<string>http://www.somsite.com/categories/2.jpg</string>
<key>country</key>
<string>EU</string>
</dict>
</array>
</dict>
</div>