Laya使用Utils工具类提供的parseXMLFromString方法,可以利用DOMParse对象将XML字符串解析为JavaScript原生的XMLDocument对象。
W3C并没有定义XMLDocument接口,因为document接口本来就是为XML定义的,而HTML只是XML的一种实现。因此需要定义HTMLDocument,但在FireFox中有一个专门的XMLDocument构造器,对document对象进行了一些扩展,通常情况下可将其当作document来使用。
针对IE浏览器
if(window.ActiveXObject && !window.DOMParser){
let xmldom = new ActiveXObject("Microsoft.XMLDOM");
xmldom.async = false;//关闭异步,无需在XML文件读取完毕前完成其它操作
xmldom.loadXML(xmlstring);//载入XML字符串
}
针对非IE浏览器
if(window.DOMParser && document.implementation && document.implementation.createDocument){
//解析XML字符串
let domparse = new DOMParser();
//解析XML字符串获取XML文档对象
let xmldom = domparse.parseFromString(xmlstring, "text/xml");
}
结构 | 描述 |
---|---|
Package | laya.utils |
Class | Laya.Utils |
Laya.Utils.parseXMLFromString(value:string):XMLDocument
class Test{
private pb = null;
constructor(){
Laya.init(Laya.Browser.clientWidth, Laya.Browser.clientHeight);
Laya.Stat.show();
this.initStage();
this.run();
}
initStage():void{
Laya.stage.autoSize = false;
Laya.stage.frameRate = "slow";
Laya.stage.screenMode = "horizontal";
Laya.stage.scaleMode = "exactfit";
Laya.stage.mouseEnabled = false;
Laya.stage.alignH = "center";
Laya.stage.alignV = "middle";
Laya.stage.bgColor = "#808080";
}
run(){
let xml = '';
xml += '<xml>';
xml += '<ToUserName><![CDATA[gh_c2********98]]></ToUserName>';
xml += '<FromUserName><![CDATA[o-BAy0********diCIE]]></FromUserName>';
xml += '<CreateTime>1132690210</CreateTime>';
xml += '<MsgType><![CDATA[event]]></MsgType>';
xml += '<Event><![CDATA[VIEW]]></Event>';
xml += '<EventKey><![CDATA[https://****.***.***/index.html]]></EventKey>';
xml += '<MenuId>400000089</MenuId>';
xml += '</xml>';
try{
let xmldoc = Laya.Utils.parseXMLFromString(xml);
console.log(xmldoc);//#document
//获取根节点
let root = xmldoc.firstChild;
console.log(root);
//获取子节点
let nodelist = root.childNodes;
console.log(nodelist);//NodeList(7) [tousername, fromusername, createtime, msgtype, event, eventkey, menuid]
//遍历子节点
for(let i=0; i<nodelist.length; i++){
//获取节点
let node = nodelist[i];
if(node.nodeType == 1){
//元素节点
console.log(i, node.nodeName, node.firstChild.nodeValue);
}else if(node.nodeType == 3){
//文本节点
console.log(i, node.nodeName, node.nodeValue);
}
}
}catch(e){
console.error(e.message);
}
}
}
new Test();
//获取根节点
let root = xmldoc.firstChild;
console.log(root);
let nodelist = root.childNodes;
console.log(nodelist);//NodeList(7) [tousername, fromusername, createtime, msgtype, event, eventkey, menuid]
console.log(i, node.nodeName, node.firstChild.nodeValue);