接上篇,本篇文章主要实现使用javascript dom 处理XSL显示数据的第二种方式。
主要代码如下:
var xmlDoc;
var xslDoc;
// 判断浏览器的类型
if(document.implementation && document.implementation.createDocument)
{
// 支持Mozilla浏览器
try
{
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.async = false;
xmlDoc.load("guestbook/guestbook.xml");
xslDoc = document.implementation.createDocument("", "", null);
xslDoc.async = false;
xslDoc.load("guestbook/guestbook.xsl");
// 定义XSLTProcessor对象
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xslDoc);
// transformToDocument方式
var result = xsltProcessor.transformToDocument(xmlDoc);
var xmls = new XMLSerializer();
document.getElementById("guestbookPanel").innerHTML = xmls.serializeToString(result);
}
catch(e)
{
alert("Unable to do xml/xsl processing");
}
}
else if(typeof window.ActiveXObject != 'undefined')
{
try
{
// 支持IE浏览器
xmlDoc = new ActiveXObject('Msxml2.DOMDocument');
xslDoc = new ActiveXObject('Msxml2.DOMDocument');
xmlDoc.async = false;
xslDoc.async = false;
xmlDoc.load("guestbook/guestbook.xml");
xslDoc.load("guestbook/guestbook.xsl");
guestbookPanel.innerHTML = xmlDoc.documentElement.transformNode(xslDoc);
}
catch(e)
{
alert("Unable to do xml/xsl processing");
}
}
else
{
alert("Browser unknown!");
}
(注:由于代码简单,故没有写多少注释敬请谅解。)