一般来说,xml文件都是从外部载入的,那么我们如何只用js生成xml对象呢?下面的程序实现了这一点,只需要输入字符串形式的xml数据,就可以转换为xml对象,并且兼容firefox。
一、
<script>
if(!document.all)
XMLDocument.prototype.__defineGetter__("xml",function(){return new XMLSerializer().serializeToString(this)})
function createXml(str){
if(document.all){
var xmlDom=new ActiveXObject("Microsoft.XMLDOM")
xmlDom.loadXML(str)
return xmlDom
}
else
return new DOMParser().parseFromString(str, "text/xml")
}
xml=createXml(document.getElementById("x1").innerHTML)
</script>
二、
XMLDocument.prototype.LoadXML
=
function
(xmlString)
{
var
childNodes
=
this
.childNodes;
for
(
var
i
=
childNodes.length
-
1
; i
>=
0
; i
--
)
this
.removeChild(childNodes[i]);
var
dp
=
new
DOMParser();
var
newDOM
=
dp.parseFromString(xmlString,
"
text/xml
"
);
var
newElt
=
this
.importNode(newDOM.documentElement,
true
);
this
.appendChild(newElt);
}
===================================================
下面是自己项目的总结:
发现在firefox下不支持xmlDom.loadXML方法和xmlDom.transformNode方法。
经过测试找到了相应的解决办法,代码如下:
=================================================================
//如果是ie
if (window.ActiveXObject){
// Load XML
var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
xmlDom.async = false;
xmlDom.loadXML(returnStr);
// Load XSL
var xsl = new ActiveXObject("Microsoft.XMLDOM");
xsl.async = false;
xsl.load("pages/siteSpread/bpis_balance.xsl");
// Transform
document.getElementById('bpisBalanceBlock').innerHTML = xmlDom.transformNode(xsl);
}else{//如果是firefox
if (document.implementation && document.implementation.createDocument){
// Load XML
var xmlDom = document.implementation.createDocument("","",null);
xmlDom.async = false;
//在FireFox中,XMLDOM只能载入处部XML文件,即FireFox下只支持XMLDom.load(xml文件),为此自己实现了一个方法
xmlDom.LoadXML(returnStr.replaceAll("\n","\n",""));
// Load XSL
var xsl = document.implementation.createDocument("","",null);
xsl.async = false;
xsl.load("pages/siteSpread/bpis_balance.xsl");
// Transform
var xslProc = new XSLTProcessor();
xslProc.importStylesheet(xsl);
var viewNode = xslProc.transformToFragment(xmlDom, document);
document.getElementById('bpisBalanceBlock').innerHTML='';
document.getElementById("bpisBalanceBlock").appendChild(viewNode);
}
}
=================================================
自实现的支持firefox的LoadXML方法
XMLDocument.prototype.LoadXML = function(xmlString){
var childNodes = this.childNodes;
for (var i = childNodes.length - 1; i >= 0; i--)
this.removeChild(childNodes[i]);
var dp = new DOMParser();
var newDOM = dp.parseFromString(xmlString, "text/xml");
var newElt = this.importNode(newDOM.documentElement, true);
this.appendChild(newElt);
}