調用xsl來解析xml文檔(js異步
1.新建一個vs2003的web工程,取名為XMLTest
2.將工程目錄下的WebForm1.aspx中內容全部刪除,只留下頂部的一條語句:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="XMLTest.WebForm1" %>
3.修改WebForm1.aspx.cs中內容,在Page_Load中加入:
??? XmlDocument doc=new XmlDocument();
??? String xmlfile=string.Empty;
??? xmlfile=Context.Request.PhysicalApplicationPath+(Request.QueryString["sel"].ToString()=="xml"?"\\hello.xml":"\\hello.xsl");
??? doc.Load(xmlfile);
??? Response.Write(doc.InnerXml);
4.在工程根目錄下新增test.htm,并設為工程首頁:
<html>
<head>
? <title></title>
</head>
<body>
? <div id="resTree"></div>
? <FONT face="宋體"></FONT><input type="button" value="執行" onclick="GetXml()"><BR>
? <script language="JScript">
? var srcTree,xsltTree,xt;
? var http_request = false;
??
? function GetXml()
? {???
?? srcTree = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
??? srcTree.async=false;
??? xsltTree= new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
??? xsltTree.async = false;
??? xt=new ActiveXObject("MSXML2.XSLTemplate");
?? resTree.innerHTML="";
??? makeRequest("WebForm1.aspx?sel=xml",GetXml_CB);
? }
???
??? function makeRequest(url,callback) {
??????? http_request = false;
??????? if (window.XMLHttpRequest) { // Mozilla, Safari,...
??????????? http_request = new XMLHttpRequest();
??????????? if (http_request.overrideMimeType) {
??????????????? http_request.overrideMimeType('text/xml');
??????????? }
??????? } else if (window.ActiveXObject) { // IE
??????????? try {
??????????????? http_request = new ActiveXObject("Msxml2.XMLHTTP");
??????????? } catch (e) {
??????????????? try {
??????????????????? http_request = new ActiveXObject("Microsoft.XMLHTTP");
??????????????? } catch (e) {}
??????????? }
??????? }
??????? if (!http_request) {
??????????? alert('Giving up :( Cannot create an XMLHTTP instance');
??????????? return false;
??????? }
??????? http_request.onreadystatechange = callback;
??????? http_request.open('GET', url, true);
??????? http_request.send(null);
??? }
??? function GetXml_CB() {
??????? if (http_request.readyState == 4) {
??????????? if (http_request.status == 200) {???
??? srcTree.loadXML(http_request.responseText);
??? makeRequest("WebForm1.aspx?sel=xsl",GetXsl_CB);
??????????? } else {
??????????????? alert('There was a problem with the request.');
??????????? }
??????? }
??? }
???
??? function GetXsl_CB(){
?????? if (http_request.readyState == 4) {
???????? if (http_request.status == 200) {
?????? xsltTree.loadXML(http_request.responseText);
?????? xt.stylesheet=xsltTree;
?????? var proc=xt.createProcessor();
?????? proc.input=srcTree;
?????? proc.transform();
?????? resTree.innerHTML=proc.output;
??????????? } else {
??????????????? alert('There was a problem with the request.');
??????????? }
??????? }
?
??? }
??? function makeRequest(url,callback) {
???? http_request = false;
???? if (window.XMLHttpRequest) { // Mozilla, Safari,...
??????????? http_request = new XMLHttpRequest();
??????????? if (http_request.overrideMimeType) {
??????????????? http_request.overrideMimeType('text/xml');
??????????? }
??????? } else if (window.ActiveXObject) { // IE
??????????? try {
??????????????? http_request = new ActiveXObject("Msxml2.XMLHTTP");
??????????? } catch (e) {
??????????????? try {
??????????????????? http_request = new ActiveXObject("Microsoft.XMLHTTP");
??????????????? } catch (e) {}
??????????? }
??????? }
??????? if (!http_request) {
??????????? alert('Giving up :( Cannot create an XMLHTTP instance');
??????????? return false;
??????? }
??????? http_request.onreadystatechange = callback;
??????? http_request.open('GET', url, true);
??????? http_request.send(null);
??? }
? </script>
</body>
</html>
5.運行工程,看看效果吧!
hello.xml(注意:我的xml文檔中并沒有指定對應的xsl解析文件名)
<?xml version='1.0'?>
<breakfast-menu>
? <food>
??? <name>Belgian Waffles</name>
??? <price>$5.95</price>
??? <description>Two of our famous Belgian Waffles
????? with plenty of real maple syrup.</description>
??? <calories>650</calories>
? </food>
? <food>
??? <name>Strawberry Belgian Waffles</name>
??? <price>$7.95</price>
??? <description>Light Belgian waffles covered with
???? strawberries and whipped cream.</description>
??? <calories>900</calories>
? </food>
? <food>
??? <name>Berry-Berry Belgian Waffles</name>
??? <price>$8.95</price>
??? <description>Light Belgian waffles covered
????? with an assortment of fresh berries
????? and whipped cream.</description>
??? <calories>900</calories>
? </food>
? <food>
??? <name>French Toast</name>
??? <price>$4.50</price>
??? <description>Thick slices made from our homemade
???? sourdough bread.</description>
??? <calories>600</calories>
? </food>
? <food>
??? <name>Homestyle Breakfast</name>
??? <price>$6.95</price>
??? <description>Two eggs, bacon or sausage, toast,
????? and our ever-popular hash browns.</description>
??? <calories>950</calories>
? </food>
</breakfast-menu>
hello.xsl
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"? xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
? <xsl:template match="/breakfast-menu">
??????? <xsl:for-each select="food">
????????? <DIV STYLE="background-color:teal; color:white; padding:4px">
??????????? <SPAN STYLE="font-weight:bold; color:white"><xsl:value-of select="name"/></SPAN>
??????????? 至 <xsl:value-of select="price"/>
????????? </DIV>
????????? <DIV STYLE="margin-left:20px; margin-bottom:1em; font-size:10pt">
??????????? <xsl:value-of select="description"/>
??????????? <SPAN STYLE="font-style:italic">
????????????? <xsl:value-of select="calories"/> 嘿嘿
??????????? </SPAN>
????????? </DIV>
??????? </xsl:for-each>
? </xsl:template>
</xsl:stylesheet>
xml文檔只有純粹的數據,如果需要顯示到html頁面中的話,一般需要使用定制的xsl文檔來解析,或者手工通過js來讀取xml中的值顯示到html中的dom樹中,當使用xsl文檔來解析時,相應的xml文檔中必須指定對應的xsl文檔才能正常顯示,但當有些程序動態輸出xml文檔時,并沒有指定相應的xsl文檔,這時就必須通過其它途徑來加載相應的xsl文檔來解析,當然,在服務器端輸出xml文檔時,通過一些xml api也可以實現,我這兒描述的是通過js來實現的一種方式。用這種方式的話,就拋開了服務器平臺的限制,服務器端只需要輸出相應的xml文檔(.net/j2ee都可以),并且將對應的xsl文檔輸出給客戶端(可以輸出流或直接在客戶端加載xsl文檔)。
這里有幾個需要注意的地方,我們一般是使用Msxml2.Document組件來加載xml文檔的,但當動態使用xsl解析xml文檔時,必須使用Msxml2.FreeThreadedDOMDocument這種自由線程的組件,同時使用MSXML2.XSLTemplate模板組件來加載xml,xsl數據,通過MSXML2.XSLTemplate的transform方法,就可以動態的用xsl來解析xml數據了,另外,IE5開始,系統默認的xml組件是msxml2,如果需要使用更新的msxml組件需要安裝更新的msxml組件包,并指定新的名稱,例如Msxml2.FreeThreadedDOMDocument.4.0,現在最新的msxml組件是6.0beta,可在M$網站下載。