日期:2014-05-16 浏览次数:20442 次
// JavaScript Document
function parseXML(filename){
var xmlDoc;
try { //Internet Explorer
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
} catch (e) {
try { //Firefox, Mozilla, Opera, etc.
xmlDoc = document.implementation.createDocument("", "", null);
} catch (e) { }
}
//关闭异步加载,这样确保在文档完全加载之前解析器不会继续脚本的执行。
xmlDoc.async=false;
//解析器加载名为 "xxx.xml" 的 XML 文档、
xmlDoc.load(filename);
return xmlDoc;
}
var nodes = parseXML('china.xml').getElementsByTagName("province");//得到所有province节点
//province对象
function Province(city,name,id) {
this.name = name;
this.city = city;
this.id=id;
this.toString = function () {
return this.name+"|"+this.city+"|"+"-->"+this.id;
}
}
//city对象
function City(province,name,id) {
this.name = name;
this.province = province;
this.id = id;
this.toString = function () {
return this.name+"|";
}
}
//让一个documents的节点转化成的provine的节点对象
function listprovince() {
var arr = new Array();
for(var i=0;i<nodes.length;i++) {
var province = new Province();
province.name = nodes[i].getAttribute('name');
province.id = i;
var nodess = nodes[i].getElementsByTagName('city');
var citys = new Array();
for(var j=0;j<nodess.length;j++) {
var city = new City(province,"");
city.id = i+"_"+j;
city.name = nodess[j].firstChild.data;
citys[j] = city;
}
province.city = citys;
arr[i]=province;
}
return arr;
}
//将一个op对象添加到指定的select下面
function toOption(op2s,des) {
for(var i=0;i<op2s.length;i++) {
var op = document.createElement("option");
op.setAttribute("value",op2s[i].id);
var name = op2s[i].name;
op.setAttribute("name",name);
op.innerHTML = name;
des.appendChild(op);
}
}
//操作china.xml文件
function test() {
var provinces = listprovince();
var sele = document.getElementById("province");
var sele1 = document.getElementById("city");
var id = sele.value;
id=id?id:0;
sele.innerHTML = null;
toOption(provinces,sele);