Reputation: 2845
I am receiving an xml data like the example below from a remote api. Could anyone show me how I can get the key names and their corresponding key values and print them? For example I want to print all categoryIcon and category values.
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 to parse:
<?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>
edit:
For each set of dict i want to print a <tr>
just like this:
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);
Upvotes: 0
Views: 3418
Reputation: 21489
First you need to parses string into an XML document using parseXML()
then you can find your key/value in document. You should find key
tag in array
tag and iterate it using .each()
. Also value of key
is in next string
tag that you can use .next()
to select it.
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>
Upvotes: 1