I was recently working on a project which requires parsing html from a .net service return Xml. It’s pretty simple technique and a useful thing for any javascript/ajax developer
First I will demonstrate how to parse html from xml
Here’s the xml structure which a .net service returns
<properties> <property> <id>18</id> <city>Abu Hamourq</city> <type>Villa</type> <long>25.1321</long> <lat>58.13131</lat> <price>10000 QAR</price> <image>/Images/Property/16/thumbnail/thumbnail2.jpg</image> </property> <property> <id>19</id> <city>Abu Hamour2</city> <type>Apartment</type> <long>25.1321</long> <lat>58.13131</lat> <price>10000 QAR</price> <image>/Images/Property/16/thumbnail/thumb1.jpg</image> </property> </properties>
and below the html structure needs to be generated
<ul> <li> <div class="image"><img src="/Images/Property/16/thumbnail/thumbnail2.jpg" /></div> <div class="Desc"> City : Abu Hamourq<br /> Type : Villa<br /> Price : 10000 QAR<br /> Latitude : 25.1321<br /> Longitude : 25.1321<br /> </div> </li> <li> <div class="image"><img src="/Images/Property/16/thumbnail/thumb1.jpg" /></div> <div class="Desc"> City : Abu Hamour2<br /> Type : Apartment<br /> Price : 10000 QAR<br /> Latitude : 25.1321<br /> Longitude : 25.1321<br /> </div> </li> </ul>
the javascript function which calls the service and loops through the xml and parse html in a
- list
function getDatafromService(){
/*.net service url which returns the xml, the querystring values filters the result*/
var xmlServiceURI = "/getData.svc?filterstring=filterstringval";
/*variable to hold html markup */
var htmlMarkup = "<ul>";
/* jquery ajax function */
$.ajax({
type: "GET",
url: xmlServiceURI,
dataType: 'xml',
success: function(xmlData){
$(xmlData).find("property").each(function(){
htmlMarkup = htmlMarkup + "<li>" +
htmlMarkup = htmlMarkup + "<div class=/"image/"><img src=/""+ $(this).find("image").text() +"" /></div>"+
htmlMarkup = htmlMarkup + "<div class=/"Desc/">"+
htmlMarkup = htmlMarkup + "City : "+ $(this).find("city").text() +"<br />" +
htmlMarkup = htmlMarkup + "Type : "+ $(this).find("type").text() +"<br />" +
htmlMarkup = htmlMarkup + "Price : "+ $(this).find("price").text() +"<br />"+
htmlMarkup = htmlMarkup + "Latitude : " + $(this).find("lat").text() + "<br />"+
htmlMarkup = htmlMarkup + "Longitude : " + $(this).find("long").text() +"<br />"+
htmlMarkup = htmlMarkup + "</div>" +
htmlMarkup = htmlMarkup + "</li>";
});
/* closing ul */
htmlMarkup = htmlMarkup +"</ul>";
/* appending the markup to <div id="Content"> in the page */
$("#Content").html(htmlMarkup);
},
error:function(){
$("#Content").html("Sorry there's an error ');
}
}
Hope it helps.. Cheers!
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.