I have little experience parsing xml documents so please bear with me. For the past few days I am struggling to parse the xml sample given below!
After searching internet and reading others comments I came to conclusion that the best way is to use $parseXML for the type of xml that I deal with.
I validated the xml and used the following code but I keep getting invalid xml! My goal is to get all string values that belong to one <dict>
and use them inside <tr>
. So I appreciate if an expert help me fix this broken code.
This is the way i want to place the key values inside div:
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);
javascript :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
function myfunction(){
alert("me here");
var 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>';
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
$($xml).each(function(){
//alert($(this).find("dict>string").text());
//alert($(this).find("dict>key").text());
alert($(this).find("dict>categoryIcon>string").text());
});
};
</script>
</head>
<body>
<button onclick="myfunction()">parse</button>
</body>
</html>
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>