javascript之XML DOM的解析
- - ITeye博客javascript之XML DOM的解析. . 长春 . 吉林市 . 四平 . 松原 . 通化 . .
javascript之XML DOM的解析
一、xml文件的定义
<?xml version="1.0" encoding="gbk"?> <china> <province name="吉林省"> <city>长春</city> <city>吉林市</city> <city>四平</city> <city>松原</city> <city>通化</city> </province> <province name="辽宁省"> <city>沈阳</city> <city>大连</city> <city>鞍山</city> <city>抚顺</city> <city>铁岭</city> </province> <province name="山东省"> <city>济南</city> <city>青岛</city> <city>威海</city> <city>烟台</city> <city>潍坊</city> </province> </china>
二、xml文件解析器的util类(跨浏览器)
function parseXML(fileXmlName){ var xmlDoc; try { //Internet Explorer 创建一个空的xml文档 xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); } catch (e) { try { //Firefox, Mozilla, Opera, 创建一个空的xml文档 xmlDoc = document.implementation.createDocument("", "", null); } catch (e) { } } //关闭异步加载 xmlDoc.async = false; //加载xml文件 xmlDoc.load(fileXmlName); return xmlDoc; }
三、XML DOM访问节点
<html> <head> <title>test01.html</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="util.js"></script> </head> <body> <select id="province" name="province"> <option value="">请选择....</option> <option value="吉林省">吉林省</option> <option value="辽宁省">辽宁省</option> <option value="山东省">山东省</option> </select> <select id="city" name="city"> <option value="">请选择.....</option> </select> </body> <script language="JavaScript"> //获取第一个下拉选择框时,显示对应的省份信息 document.getElementById("province").onchange = function () { //处理上一级节点的值 var cityElement = document.getElementById("city"); var optionElements =cityElement.getElementsByTagName("option"); for(var z=1;z<optionElements.length;z++){ cityElement.removeChild(optionElements[z]); z--; } //1.获取页面选中的省份信息 var provinceElement = this.value; //2.创建xml解析器,参数传递xml文件 var docXml = parseXML("cities.xml"); //3.获取xml文件所有对应的province标签 var provinceXmlElements = docXml.getElementsByTagName("province"); //4.遍历province标签 for (var i = 0; i < provinceXmlElements.length; i++) { var provinceXmlElement = provinceXmlElements[i]; var provinceXmlValue = provinceXmlElement.getAttribute("name"); //5.对比(页面==xml) if (provinceXmlValue == provinceElement) { //6.获取获取xml文件所有对应的province下的所有city标签 var cityXmlElements = provinceXmlElement.getElementsByTagName("city"); //7.遍历city标签 for (var j = 0; j < cityXmlElements.length; j++) { var cityXmlElement = cityXmlElements[j]; // var cityXmlValue = cityXmlElement.fistChild.nodeValue; var cityXmlValue = cityXmlElement.text; //8.增加city值 var optionElement = document.createElement("option"); optionElement.setAttribute("value", cityXmlValue); var text = document.createTextNode(cityXmlValue); optionElement.appendChild(text); cityElement.appendChild(optionElement); } } } } </script> </html>
四、XML DOM 操作 XML文档
XML DOM中创建节点,删除节点,移动节点,读写节点数据等操作与HTML DOM的操作相同