当前位置:Web前端 > jquery> 正文

jquery解析xml

时间:2014-8-3类别:Web前端

jquery解析xml

jquery解析xml

一、jquery解析xml步骤

 

1、获取XML

  •  
  • JScript 代码   复制
  • 
    $(document).ready(function() {
        $.ajax({
            url: '/xml/books。xml',
            type: 'GET',
            dataType: 'xml',
            timeout: 1000,  //设定超时
            cache: false,   //禁用缓存
            error: function(xml) {
                alert("加载XML文档出错!");
            },
            success: GetStudentComplete   //设置成功后回调函数
        });
    });
    
    		
  •  

    2、解XML

  •  
  • JScript 代码   复制
  • 
    //获取XML成功后回调函数
    function GetStudentComplete(xml) {
        $(xml).find("student").each(function(i) {     //查找所有student节点并遍历
            var id = $(this).children("id");          //获得子节点
            var id_vaule = id.text();                 //获取节点文本
            var email_vaule = $(this).attr("email");  //获取节点的属性
            alert(id_vaule);
            alert(email_vaule);
        });
    }
    
    		
  •  

     

    二、jquery解析xml完整实例

     

    1、xml文件结构:books。xml

  •  
  • 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>
    
    		
  •  

    2、页面代码

  •  
  • HTML 代码   复制
  • 
    <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.7.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>";
                });
                $('#myli').html(s);
            });
        });
    </script>
    </head>
    <body>
        <li id='myli'></li>
    </body>
    </html>
    
    		
  •  

    3、效果图

     

    标签:
    上一篇下一篇

    猜您喜欢

    热门推荐