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

js读取xml
请问js怎么读取xml数据呢?给个最简单的例子好吗?谢谢~~~~~

------解决方案--------------------
读取xml联动下拉框:

---location.xml-----
<?xml version= "1.0 " encoding= "GB2312 " ?>
<location>
<province name= "广东 ">
<city name= "深圳 " value= "0101 " />
<city name= "广州 " value= "0102 " />
</province>
<province name= "四川 ">
<city name= "成都 " value= "0201 " />
</province>
<province name= "江西 ">
<city name= "南昌 " value= "0301 " />
<city name= "九江 " value= "0302 " />
<city name= "吉安 " value= "0303 " />
<city name= "新余 " value= "0304 " />
<city name= "赣州 " value= "0305 " />
<city name= "宜春 " value= "0304 " />
</province>
<province name= "山东 ">
<city name= "济南 " value= "0401 " />
<city name= "青岛 " value= "0402 " />
</province>
</location>

-------test.html-------
<select id= "select1 " onchange= "change1() ">
</select>

<select id= "select2 " onchange= "alert(this.value) ">
</select>


<Script Language= "Javascript ">

var xmlDoc;
function init(){
xmlDoc = new ActiveXObject( "Microsoft.XMLDOM ");
xmlDoc.load( "location.xml ");

if(xmlDoc.parseError.errorCode != 0)
{
alert( "You have error " + xmlDoc.parseError.reason);
return;
}


var e = xmlDoc.documentElement.selectNodes( "/location/province ");
var select1=document.getElementById( "select1 ");
var select2=document.getElementById( "select2 ");

for(i=0;i <e.length;i++)
{
select1.add(new Option(e[i].getAttribute( "name ").toString(),e[i].getAttribute( "name ").toString()))
}
var city=e.item(0).selectNodes( "./city ");
for(j=0;j <city.length;j++)
{
select2.add(new Option(city.item(j).getAttribute( "name ").toString(),city.item(j).getAttribute( "value ").toString()))
}
}

function change1()
{
var select1=document.getElementById( "select1 ");
var select_result=select1.value;
var opts=document.getElementById( "select2 ").options;
opts.length=0;
var e = xmlDoc.documentElement.selectNodes( "/location/province[@name= ' "+select_result+ " '] ");
var city=e.item(0).selectNodes( "./city ");
for(j=0;j <city.length;j++)
{
select2.add(new Option(city.item(j).getAttribute( "name ").toString(),city.item(j).getAttribute( "value ").toString()))
}
}

init();
</Script>