It is delightful to find an elegant way to read, parse XML file and put parts of its content to the HTML file on the fly. It would be cumbersome for a HTML file if it
keeps all the content in itself. And we can separate the content and its way of presentation. Thanks to the jQuery Ajax function. Terse and easy. Save me lots of efforts!
1. First you may have a XML file like this:
<project type="group">
<name>MyEBag</name>
<time>2009 Fall</time>
<description>Online Transaction Processing</description>
<skill>Oracle</skill>
<skill>SQL</skill>
</project>
<project type="group">
<name>MOCC</name>
<time>2010 Fall</time>
<description>Museum website</description>
<skill>JSP</skill>
<skill>Javascript</skill>
<skill>SQL</skill>
</project>
2. in the HTML file,
//put the code in the jQuery document ready function, the code will be loaded after the page is loaded
$(document).ready(function(){
$.ajax({
type: "GET",
url: "project.xml", //the xml file name
dataType: "xml",
success: function(xml){ // if the xml file is loaded successfully then execute....
//for each project, append its name to the html element id=#prjdesc
//"project" and "name" are the labels in the xml file
$(xml).find("project").each(function(){
$("#prjdesc").append("<h3>"+$(this).find("name").text()+"</h3>");
$("#prjdesc").append($(this).attr("type"));
$("#prjdesc").append($(this).find("time").text());
});
}
});
3. the html file may end like this
<div id="#prjdesc">
<h3>MyEBag</h3>
group2009Fall
<h3>MOCC</h3>
group2010Fall
</div>
Reference: XML.com
No comments:
Post a Comment