Ajax技术(7)--AJAX解析XML

前端之家收集整理的这篇文章主要介绍了Ajax技术(7)--AJAX解析XML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、用ajax原生方式解析xml数据。

js 代码

 1     <SCRIPT LANGUAGE="JavaScript">   
2 var xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
3 xmlHttp.open("GET","AJAX",true);
4 /* 设置处理服务器的JS函数函数又 xmlHttp.onreadystatechange来确定 */
5 xmlHttp.onreadystatechange=function() {
6 if (xmlHttp.readyState==4 && xmlHttp.status==200) {
7 //ajax的XML传输的解析。获取解析的数据
8 var xml = xmlHttp.responseXML;
9
10 解析标签<stusn> 11 var root1=root.getElementsByTagName("stusn"); 12 解析<stusn>的第一个标签的nation属性 13 var name = root1[0].getAttribute("nation"); 14 var div1 = document.getElementById("ccc");
15 var stus = xml.getElementsByTagName("stu");
16 for(var i = 0 ; i < stus.length ; i++){
17 var dl = document.createElement("dl");
18 var dt = document.createElement("dt");
19 var dd = document.createElement("dd");
20 在div的最前面添加元素 21 div1.insertBefore(dl,div1.firstChild);
22 dl.appendChild(dt);
23 dl.appendChild(dd);
24 设置元素的值 25 dt.innerHTML = "姓名:" + stus[i].getElementsByTagName("name")[0].firstChild.data;
26 dd.innerHTML = "年龄:" + stus[i].getElementsByTagName("age")[0].firstChild.data;
27 }
28 }
29 }
30 xmlHttp.send();
31 </script>

后台处理代码

java 代码
 1     import java.io.IOException;   
2 import java.io.PrintWriter;
3
4 import javax.servlet.ServletException;
5 import javax.servlet.http.HttpServlet;
6 import javax.servlet.http.HttpServletRequest;
7 import javax.servlet.http.HttpServletResponse;
8
9 public class AJAXParseXML extends HttpServlet {
10
11 /**
* Constructor of the object.
14 public AJAXParseXML() {
15 super();
16 }
17
18 19 * Destruction of the servlet. <br>
20 21 void destroy() {
22 super.destroy(); Just puts "destroy" string in log
23 Put your code here 24 }
25
26 void doGet(HttpServletRequest request,HttpServletResponse response)
27 throws ServletException,IOException {
28
29 如果要传输XML,则需要设置传输的类型为text/xml 30 response.setContentType("text/xml;charset=gb2312");
31 response.setHeader("Cache-Control","no-cache");
32 PrintWriter out = response.getWriter();
33 out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
34 out.println("<stusn nation=\"china1\" ></stusn>"); 35 TestXML tx = new TestXML();
36 tx.sendXML(out);
37 out.close();
38 }
39
40 void doPost(HttpServletRequest request,128); line-height:1.5!important">41 42
43 }
44
45 void init() throws ServletException {
46 47 48
49 }

产生XML文档的代码

java 代码
import java.io.FileOutputStream;
import java.io.OutputStream;
3 4
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
8 import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
10 import javax.xml.transform.dom.DOMSource;
11 import javax.xml.transform.stream.StreamResult;
12
13 import org.w3c.dom.Document;
14 import org.w3c.dom.Element;
15
16 class TestXML {
void sendXML(PrintWriter os){
19 Document doc ;
20 Element stus;
21 Element stu;
22 Element name;
23 Element age;
24 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
25
26 try {
27 DocumentBuilder db = dbf.newDocumentBuilder();
28
29 doc = db.newDocument();
30
31 stus = doc.createElement("stusn");
32
33 stu = doc.createElement("stu");
34
35 name = doc.createElement("name");
36 name.appendChild(doc.createTextNode("andrii"));
37
38 age = doc.createElement("age");
39 age.appendChild(doc.createTextNode("27"));
40
41 stu.appendChild(name);
42 stu.appendChild(age);
43
44 stus.setAttribute("nation","china");
45 stus.appendChild(stu);
46
47 doc.appendChild(stus);
48
49 TransformerFactory tf = TransformerFactory.newInstance();
50
51 Transformer ts = tf.newTransformer();
52 ts.transform(new DOMSource(doc),new StreamResult(new FileOutputStream("D:/test.xml"))); 53 ts.transform(new DOMSource(doc),255); line-height:1.5!important">new StreamResult(os));
54
55 } catch (Exception e) {
56 TODO Auto-generated catch block 57 e.printStackTrace();
58 }
59 }
60 }
二、xml作为单独文件存在。test.xml
<?xml version="1.0" encoding="utf-8" ?>  
<root>  
    <book id="1">  
        <name>深入浅出extjs</name>  
        <author>张三</author>  
        <price>88</price>  
    </book>  
    <book id="2">  
        <name>锋利的jQuery</name>  
        <author>李四</author>  
        <price>99</price>  
    </book>  
    <book id="3">  
        <name>深入浅出flex</name>  
        <author>王五</author>  
        <price>108</price>  
    </book>  
    <book id="4">  
        <name>java编程思想</name>  
        <author>钱七</author>  
        <price>128</price>  
    </book>  
</root>  
在Test.html中解析代码
$("#a3").click(function(){  
        $.get('test.xml',function(data){  
            var s="";  
            $(data).find('book').each(function(i){  
                var id=$(this).attr('id');  
                var name=$(this).children('name').text();  
                var author=$(this).children('author').text();  
                var price=$(this).children('price').text();  
                s+=id+"    "+name+"    "+author+"    "+price+"<br>";  
            });  
            $('#div2').html(s);  
        });  
    });

猜你在找的Ajax相关文章