`
bleach0608
  • 浏览: 60999 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

javascript解析xml

阅读更多

xml文件格式:

<?xml version="1.0" encoding="GB2312"?> 

<classmates> 
  <student> 
     <sid>1</sid> 
     <sname>reqe</sname> 
     <gre>1700</gre> 
     <tse>120</tse> 
  </student> 
  <student> 
     <sid>2</sid> 
     <sname>rqerwe</sname> 
     <gre>1800</gre> 
     <tse>120</tse> 
  </student> 
  <student> 
     <sid>3</sid> 
     <sname>iuir</sname> 
     <gre>1700</gre> 
     <tse>120</tse> 
  </student> 
</classmates> 

 解析:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  
    
    <title>JS解析XML示例</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<script type="text/javascript">
	var http = createRequestObject();
	
	function createRequestObject() {
 	// find the correct xmlHTTP, works with IE, FF and Opera
 	var xmlhttp;
	 try {
	    xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	    usewin = "msxml";
	 }
	 catch(e) {
	  try {
	      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	   	  usewin = "microsoft";
	  }
	  catch(e) {
	      xmlhttp=null;
	  }
	 }

	 if(!xmlhttp&&typeof XMLHttpRequest!="undefined") {
	  	xmlhttp=new XMLHttpRequest();
	    usewin = "undefined";
 	}
 	return  xmlhttp;
	}
	
	function sendRequest() {
	var xmlurl="MyXML.xml";
	 try{
	  http.open("GET", xmlurl, true);
	  http.setRequestHeader('Content-Type',  "text/xml");
	  http.onreadystatechange = handleResponse;
	  http.send(null);
	 }
	 catch(e){
	  // caught an error
	  alert('Request send failed.');
	 }
	 finally{}
	
	}

	function handleResponse() {
	 try{
	  if((http.readyState == 4)&&(http.status == 200)){
	   var students = XMLHttpReq.responseXML.getElementsByTagName("student"); //得到所有的student结点数组
          for(var i =0;i<students.length;i++) 
          { 
                var stud = students[i]; //得一个stutdent结点
                var name = stud.getElementsByTagName("sname")[0].firstChild.data; //取结点里的数据
                var gre = stud.getElementsByTagName("gre")[0].firstChild.data; 
                var tse = stud.getElementsByTagName("tse")[0].firstChild.data; 
          } 
		       

	   

	  }
	 }catch(e){
	  alert('Response failed.');
	 }
	 finally{}
	}
	


</script>
  </head>
  
  <body onload="sendRequest()">
   	
  </body>
</html>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics