js 解析xml文档 示例

1.测试test.xml

<?xml version="1.0" encoding="UTF-8"?>
<rautinee>

<member id='1'> 
<name>搜索</name>
<loginName>aa</loginName>
<email>[email protected]</email>
</member>

<member id='2'>
<name>地点</name>
<loginName>bb</loginName>
<email>[email protected]</email>
</member>

<member id='3'>
<name>方法</name>
<loginName>cc</loginName>
<email>[email protected]</email>
</member>

<member id='4'>
<name>广告</name>
<loginName>dd</loginName>
<email>[email protected]</email>
</member>

</rautinee>

2.js解析代码

<script>
//针对两种浏览器,分别获取xmlDocument对象
function   loadXML(xmlFile) { 
	var xmlDoc;
	if(window.ActiveXObject) { 
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); 
		xmlDoc.async=false;
		xmlDoc.load(xmlFile);
	}
	else if(document.implementation&&document.implementation.createDocument){ 
		xmlDoc=document.implementation.createDocument( "", "",null); 
		xmlDoc.async=false;
		xmlDoc.load(xmlFile);
	} else{
		alert('Your   browser   cannot   handle   this   script'); 
	}
	return xmlDoc;
}

var xmlDoc = loadXML("test.xml");
var members = xmlDoc.getElementsByTagName("member");
var maxRes = members.length;
var str="";
str += "<table>";

str += '<tr>';
str += '<td width="100">id</td>';
str += '<td width="100">name</td>';
str += '<td width="100">loginname</td>';
str += '<td width="100">email</td>';
str += '</tr>';

for(var i=0;i<maxRes;i++){

		str += '<tr>';
		
		str += '<td >' + members[i].getAttribute("id") + '</td>';
		
		var oName = members[i].getElementsByTagName("name");
		str += '<td >' + oName[0].firstChild.nodeValue + '</td>';
		
		var oLoginName = members[i].getElementsByTagName("loginName");
		str += '<td >' + oLoginName[0].firstChild.nodeValue + '</td>';

		var oEmail = members[i].getElementsByTagName("email");
		str += '<td >' + oEmail[0].firstChild.nodeValue + '</td>';
		
		str += '</tr>';
}
str += "</table>";

document.write(str);
</script>

 

你可能感兴趣的:(js 解析xml文档 示例)