这是我的一篇关于js解析xml练习的一篇文章:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title></title>
</head>
<body>
<select name="country" id="country">
<option value="">-- 请选择国家 --</option>
</select>
<select name="province" id="province">
<option value="">-- 请选择省市 --</option>
</select>
<select name="city" id="city">
<option value="">-- 请选择城市 --</option>
</select>
<select name="region" id="region" style="display:none">
<option value="">-- 请选择县 --</option>
</select>
<script type="text/javascript">
var xmlDom;
if(window.ActiveXObject){
xmlDom = new ActiveXObject("Microsoft.XMLDOM");
}else{
xmlDom = document.implementation.createDocument("","",null);
}
//alert(xmlDom);//---加载本地xml文件---并解析
xmlDom.async = false;
xmlDom.load("LocList.xml");
var countrys = xmlDom.getElementsByTagName("CountryRegion");
//第一级级联
for(var i = 0;i < countrys.length;i++){
var country = countrys[i].getAttribute("Name");
var option = new Option(country,country);
document.getElementById("country").options.add(option);
//alert(country);
}
//第二级级联
document.getElementById("country").onblur = function(){
var v = this.value; //国家
//alert(v + "^^^" + country);
for(var k = 0; k < countrys.length;k++){
var countryName = countrys[k].getAttribute("Name");
var country = countrys[k];
if(countryName == v){
var provinces = country.getElementsByTagName("State");
//alert(provinces.length);
document.getElementById("province").options.length = 1; //选择前清空
for(var j = 0;j < provinces.length;j++){
var province = provinces[j].getAttribute("Name");
var option = new Option(province,province);
document.getElementById("province").options.add(option);
}
}
}
//document.getElementById("city").options.length = 1
}
//第三级级联----省变动的时候出现三级级联
document.getElementById("province").onchange = function(){
for(var m = 0; m < countrys.length;m++){
var v2 = this.value;
var provinces = countrys[m].getElementsByTagName("State");
//alert(v2 + "&&&" + this.value);
//外国的州一般为空---暂时不可用
//中国的省市处理
for(var n = 0;n < provinces.length;n++){
var provinceName = provinces[n].getAttribute("Name");
//alert(v1 + "**" + provinceName);
var province = provinces[n];
if(provinceName == v2){
var citys = province.getElementsByTagName("City");
document.getElementById("city").options.length = 1; //选择前清空
for(var k = 0;k < citys.length;k++){
var city = citys[k].getAttribute("Name");
var option = new Option(city,city);
document.getElementById("city").options.add(option);
}
}else if(v2 == ""){
alert("aa");
}
}
}
}
document.getElementById("city").onchange = function(){
document.getElementById("region").style.display = "block";
}
</script>
</body>
</html>