一般来说,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>
二、
{
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方法。
if (window.ActiveXObject){
var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
xmlDom.async = false;
xmlDom.loadXML(returnStr);
var xsl = new ActiveXObject("Microsoft.XMLDOM");
xsl.async = false;
xsl.load("pages/siteSpread/bpis_balance.xsl");
document.getElementById('bpisBalanceBlock').innerHTML = xmlDom.transformNode(xsl);
if (document.implementation && document.implementation.createDocument){
var xmlDom = document.implementation.createDocument("","",null);
xmlDom.async = false;
xmlDom.LoadXML(returnStr.replaceAll("\n","\n",""));
var xsl = document.implementation.createDocument("","",null);
xsl.async = false;
xsl.load("pages/siteSpread/bpis_balance.xsl");
var xslProc = new XSLTProcessor();
xslProc.importStylesheet(xsl);
var viewNode = xslProc.transformToFragment(xmlDom, document);
document.getElementById('bpisBalanceBlock').innerHTML='';
document.getElementById("bpisBalanceBlock").appendChild(viewNode);
}
}
var childNodes = this.childNodes;
for (var i = childNodes.length - 1; i >= 0; i--)
this.removeChild(childNodes[i]);
var newDOM = dp.parseFromString(xmlString, "text/xml");
var newElt = this.importNode(newDOM.documentElement, true);
this.appendChild(newElt);
}