日期:2014-05-16  浏览次数:20393 次

JS解析XML文件实现两级下拉菜单的选择

??????? JavaScript在Web中深受程序员的青睐,不仅因为它可以制作很多绚丽的HTML页面特效,而且JavaScript结合HTML DOM在解析HTML、XML等文件方面更是强悍!在某些情况下,我们甚至可以完全撇开数据库,而使用XML文档作为数据存储介质开发一个网站,这样即快速又省事。

??????? 以下是我写的一个使用JS解析XML文件并实现两级下拉菜单的选择的案例。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>xmlDom.html</title>

		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="this is my page">
		<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<script type="text/javascript">
<!--
window.onload = function() {

	var xmlDom;

	try {

		//创建一个空的微软XML文档对象
		xmlDom = new ActiveXObject("Microsoft.XMLDOM");

	} catch (err1) {

		try {

			//创建一个空的其他浏览器厂商XML文档对象
			xmlDom = document.implementation.createDocument("", "", null);

		} catch (err2) {
		
			alert(err2.message);

		}

	}

	//关闭异步加载
	xmlDom.async = false;

	//加载xml文件
	xmlDom.load("city.xml");

	//获取XML文件的根节点
	var root = xmlDom.documentElement;
	
	//获取XML文件根节点的所有子节点
	var x_province = root.childNodes;

	var s_province = document.getElementById("province");

	for ( var i = 0; i < x_province.length; i++) {

		//获取属性值
		var x_pname = x_province[i].getAttribute("name");

		//创建option对象
		var option = document.createElement("option");

		option.appendChild(document.createTextNode(x_pname));

		s_province.appendChild(option);

	}

	var s_city = document.getElementById("city");

	s_province.onchange = function() {

		var opts = s_province.options;

		//获取下拉菜单中被选中项的下标(索引值)
		var opt = opts[s_province.selectedIndex];
		
		//获取option中的文本内容
		var s_pname = opt.innerHTML;

		for ( var j = 0; j < x_province.length; j++) {

			var x_pname = x_province[j].getAttribute("name");

			if (s_pname == x_pname) {

				s_city.length = 1;

				var x_pe = x_province[j];

				var x_city = x_pe.childNodes;

				for ( var k = 0; k < x_city.length; k++) {

					var ot = document.createElement("option");

					ot.appendChild(document
							.createTextNode(x_city[k].firstChild.nodeValue));

					s_city.appendChild(ot);

				}

			}

		}

	}

}
-->
</script>
	</head>

	<body>
		<h2>
			JS解析XML文件实现两级下拉菜单的选择
		</h2>
		<div>
			<span> <select name="province" id="province">
					<option>
						--请选择--
					</option>
				</select> 省 </span>
			<span> <select name="city" id="city">
					<option>
						--请选择--
					</option>
				</select> 市</span>
		</div>
	</body>
</html>
city.xml 代码清单:
<?xml version="1.0" encoding="UTF-8"?>
<china>
<province name="北京">
<city>大兴</city>
<city>昌平</city>
<city>朝阳</city>
<city>海淀</city>
<city>东城</city>
<city>西城</city>
</province>
<province name="河北">
<city>石家庄</city>
<city>保定</city>
<city>邢台</city>
<city>张家口</city>
<city>廊坊</city>
<city>承德</city>
</province>
<province name="河南">
<city>郑州</city>
<city>安阳</city>
<city>平顶山</city>
<city>开封</city>
<city>商丘</city>
<city>洛阳</city>
</province>
</china>

?