欢迎来到天天文库
浏览记录
ID:14776149
大小:40.00 KB
页数:5页
时间:2018-07-30
《javascript解析xml的方法总结》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、JavaScript解析XML的方法总结最近一个项目中要用到树形列表,本来是用mztree的,但数据用了xml,本来xml就是树形目录,就打算用JavaScript直接解析xml文件了,网上找到一些JavaScript操作xml的方法,在此做一个总结。我的xml文件Login.xml如下:<?xmlversion="1.0"encoding="utf-8"?><Login><Character><CText="热血"Value="0"></C><CText="弱气"Value="1"></C><CText="激情"Value="2"></C><CText="
2、冷静"Value="3"></C><CText="冷酷"Value="4"></C></Character><Weapon><WText="光束剑"Value="0"></W><WText="光束配刀"Value="1"></W></Weapon><EconomyProperty><PText="平均型"Value="0"></P><PText="重视攻击"Value="1"></P><PText="重视敏捷"Value="2"></P><PText="重视防御"Value="3"></P><PText="重视命中"Value="4"></P></Econo
3、myProperty></Login>现在我需要对这个xml文件的内容进行操作。首先,我们需要加载这个xml文件,JavaScript中加载xml文件,是通过XMLDOM来进行的://加载xml文档loadXML=function(xmlFile){varxmlDoc;if(window.ActiveXObject){xmlDoc=newActiveXObject('Microsoft.XMLDOM');xmlDoc.async=false;xmlDoc.load(xmlFile);}elseif(document.implementation&&docum
4、ent.implementation.createDocument){xmlDoc=document.implementation.createDocument('','',null);xmlDoc.load(xmlFile);}else{returnnull;}returnxmlDoc;}xml文件对象出来了,接下去我就要对这个文档进行操作了。比如说,我们现在需要得到节点Login/Weapon/W的第一个节点的属性,那么我们可以如下进行://首先对xml对象进行判断checkXMLDocObj=function(xmlFile){varxmlDoc=lo
5、adXML(xmlFile);if(xmlDoc==null){alert('您的浏览器不支持xml文件读取,于是本页面禁止您的操作,推荐使用IE5.0以上可以解决此问题!');window.location.href='/Index.aspx';}returnxmlDoc;}//然后开始获取需要的Login/Weapon/W的第一个节点的属性值varxmlDoc=checkXMLDocObj('/EBS/XML/Login.xml');varv=xmlDoc.getElementsByTagName('Login/Weapon/W')[0].childNo
6、des.getAttribute('Text')而我在我的程序中的写法是这样子的,当然我在程序中的写法是已经应用到实际中的了.一并给出来,以供查看。initializeSelect=function(oid,xPath){varxmlDoc=checkXMLDocObj('/EBS/XML/Login.xml');varn;varl;vare=$(oid);if(e!=null){n=xmlDoc.getElementsByTagName(xPath)[0].childNodes;l=n.length;for(vari=0;i7、n=document.createElement('option');option.value=n[i].getAttribute('Value');option.innerHTML=n[i].getAttribute('Text');e.appendChild(option);}}}上面的访问代码中,我们是通过xmlDoc.getElementsByTagName(xPath)来进行的。还可以通过xmlDoc.documentElement.childNodes(1)..childNodes(0).getAttribute('Text')进行访问。一些常用8、方法:◆xmlDoc.documentElement
7、n=document.createElement('option');option.value=n[i].getAttribute('Value');option.innerHTML=n[i].getAttribute('Text');e.appendChild(option);}}}上面的访问代码中,我们是通过xmlDoc.getElementsByTagName(xPath)来进行的。还可以通过xmlDoc.documentElement.childNodes(1)..childNodes(0).getAttribute('Text')进行访问。一些常用
8、方法:◆xmlDoc.documentElement
此文档下载收益归作者所有