轻松使用jquery解析XML

本文介绍了一个使用jQuery从XML文件中读取书籍信息并显示在网页上的示例。该示例通过jQuery的.post方法获取XML文件内容,遍历每个书籍元素,并将书籍ID、名称、作者及价格展示在页面上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

xml文件结构:books.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 >

页面代码:

<! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
< html >
< head >
< meta  http-equiv ="Content-Type"  content ="text/html; charset=UTF-8" >
< title > jquery解析xml </ title >
< script  type ="text/javascript"  src ="js/jquery-1.4.2.min.js" ></ script >
< script  type ="text/javascript" >
    $(
function () {
        $.post('books.xml',
function (data) {
            
// 查找所有的book节点
             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 + " &nbsp;&nbsp;&nbsp;&nbsp; " + name + " &nbsp;&nbsp;&nbsp;&nbsp; " + author + " &nbsp;&nbsp;&nbsp;&nbsp; " + price + " <br> " ;
            }
);
            $('#mydiv').html(s);
        }
);
    }
);
</ script >
</ head >
< body >
    
< div  id ='mydiv' ></ div >
</ body >
</ html >

效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值