jquery解析xml

来源:互联网 发布:js 屏蔽鼠标中键 编辑:程序博客网 时间:2024/06/03 21:54
1、要解析的xml文件booklist.xml 
Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <booklist>  
  3.     <book isbn='b001'>  
  4.         <name>java</name>  
  5.         <author>Gaosilin</author>  
  6.     </book>  
  7.     <book isbn='b002'>  
  8.         <name>Python</name>  
  9.         <author>卡卡</author>  
  10.     </book>  
  11. </booklist>  


2、解析并显示的html 
Java代码  收藏代码
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">  
  2. <html>  
  3.     <head>  
  4.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  5.         <title>Jquery解析xml</title>  
  6.         <script src="jquery.js"></script>  
  7.         <script type="text/javascript">  
  8.             loadbook();  
  9.               
  10.             function loadbook(){  
  11.                 //使用Ajax方式加载后再处理  
  12.                 $.ajax({  
  13.                     type:'GET',  
  14.                     url:'booklist.xml',  
  15.                     dataType:'xml',//注意处理信息的类型为xml,默认为html  
  16.                     success:function(docxml){  
  17.                         //查找并迭代<book>节点  
  18.                         $(docxml).find('book').each(function(){  
  19.                             var isbn = $(this).attr('isbn');//获取节点属性  
  20.                             var bookname = $(this).children('name').text();//获取子节点的文本值  
  21.                             var author = $(this).children('author').text();  
  22.                               
  23.                             //构造节点  
  24.                             var bookdiv = '<div><li>ISBN:'+isbn+'</li><li>书名:'+bookname+'</li><li>作者:'+author+'</li><div><br>';  
  25.                             $('#listdiv').append(bookdiv);  
  26.                         })  
  27.                     }  
  28.                 });  
  29.             }  
  30.         </script>  
  31.     </head>  
  32.     <body>  
  33.         <div id="listdiv">  
  34.               
  35.         </div>  
  36.     </body>  
  37. </html>  


3、结果 
 
0 0
原创粉丝点击