js技术实现xml文档的解析(实现省市下拉列表的级联操作)

案例演示:
city.xml
<?xml version="1.0" encoding="UTF-8"?>
<cities>
<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>

</cities>


city.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>city.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">

<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

</head>

<body>

<h1>
解析xml文件实现省市级联下拉菜单
</h1>

<div>

<span> <select id="province" name="province">
<option>
请选择省
</option>
</select> </span>

<span> <select id="cities" name="city">
<option>
请选择相应省下面的市
</option>
</select> </span>

</div>
</body>
</html>

<script>
window.onload = function() {
var xmlDom;
try {
//针对的是IE浏览器 创建一个空的微软 XML 文档对象
xmlDom = new ActiveXObject("Microsoft.XMLDOM");
} catch (err) {
try {
//在 Firefox 及其他浏览器中的 XML 解析器
//创建一个空的 XML 文档对象。
xmlDom = document.implementation.createDocument("", "", null);
} catch (e) {
}
}

//关闭异步加载,这样确保在文档完全加载之前解析器不会继续脚本的执行
xmlDom.async = "false";

//解析器加载名为 "xxx.xml" 的 XML 文档、
xmlDom.load("city.xml");

//获取xml文件的根节点
var root = xmlDom.documentElement;

//获取根节点下面的省节点
var provinces = root.childNodes;

var province = document.getElementById("province");
for ( var i = 0; i < provinces.length; i++) {
//获取省节点的name属性的值
var name = provinces[i].getAttribute("name");
//创建一个option
var opt = document.createElement("option");
//为option添加文本
opt.appendChild(document.createTextNode(name));
//添加到父节点中
province.appendChild(opt);

}

var cities = document.getElementById("cities");
province.onchange = function() {
var pce = document.getElementById("province");
var opts = pce.options;
var opt1 = opts[pce.selectedIndex];

var name = opt1.innerHTML;
for ( var i = 0; i < provinces.length; i++) {
//获取省节点的name属性的值
var name1 = provinces[i].getAttribute("name");
if (name == name1) {
    cities.length=1;//每次改变的时候清空
var pros = provinces[i];
var citys = pros.childNodes;
alert(citys.length+"====================");
for ( var j = 0; j < citys.length; j++) {
//创建一个option
var opt1 = document.createElement("option");
//为option添加文本
opt1.appendChild(document.createTextNode(citys[j].firstChild.nodeValue));
//添加到父节点中
cities.appendChild(opt1);
}
}

}

}

}
</script>

你可能感兴趣的:(xml,浏览器,IE,J#,firefox)