一:使用传统JavaScript调用XML的方法(使用Get方式获得数据)
<head> <title>使用传统JavaScript调用XML的方法</title> <script type="text/javascript"> //加载xml文件 function loadXML(xmlFile) { var xmlDoc, xmlhttp; if (window.XMLHttpRequest) {//兼容 IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {//兼容 IE5、IE6 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET", xmlFile, false); //使用HTTP GET初始化HTTP请求 xmlhttp.send(); //发送HTTP请求并获取HTTP响应 xmlDoc = xmlhttp.responseXML; //获取XML文档 return xmlDoc; } //按钮单击事件 function btn_Click() { var strHTML = ""; //初始化保存内容变量 var NewXmlDoc = loadXML("Xml/7-4.xml"); var NewTmpTag = NewXmlDoc.getElementsByTagName("User"); //获得标签 strHTML += "姓名:" + NewTmpTag[0].getElementsByTagName("name")[0].firstChild.nodeValue + "<br>"; strHTML += "性别:" + NewTmpTag[0].getElementsByTagName("sex")[0].firstChild.nodeValue + "<br>"; strHTML += "邮箱:" + NewTmpTag[0].getElementsByTagName("email")[0].firstChild.nodeValue + "<hr>"; document.getElementById("Tip").innerHTML = strHTML; //显示处理后的数据 } </script> </head> <body> <div class="iframe"> <div class="title"> <input type="button" onclick="btn_Click()" class="btn" value="获取数据" /> </div> <div class="content"> <div id="Tip"></div> </div> </div> </body> </html>
二、jQuery方式解析XML数据
<head> <title>jQuery 解析XML 数据</title> <script src="JScript/jquery-1.8.2.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { $("#Button1").click(function() { //按钮单击事件 var strHTML = ""; //初始化保存内容变量 $.ajax({ url: 'Xml/7-5.xml', dataType: 'xml', success: function(data) { var $strUser = $(data).find("User"); strHTML += "编号:" + $strUser.attr("id") + "<br>"; strHTML += "姓名:" + $strUser.children("name").text() + "<br>"; strHTML += "性别:" + $strUser.children("sex").text() + "<br>"; strHTML += "邮箱:" + $strUser.children("email").text() + "<hr>"; $("#Tip").html(strHTML); //显示处理后的数据 } }); }); }); </script> </head> <body> <div class="iframe"> <div class="title"> <input id="Button1" type="button" class="btn" value="获取数据" /> </div> <div class="content"> <div id="Tip"></div> </div> </div> </body> </html>
xml
<?xml version="1.0" encoding="utf-8" ?> <Info> <User id="10001"> <name>小明</name> <sex>男</sex> <email>124@163.com</email> </User> </Info>
参考地址:http://www.cnblogs.com/wujy/p/3539849.html