【问题标题】:jQuery XML parsing - Getting attribute valuesjQuery XML 解析 - 获取属性值
【发布时间】:2013-09-05 04:22:50
【问题描述】:

我在通过 Ajax 发送请求后得到以下 xml 响应,所以我想使用 jQuery 解析以下 xml 数据以获取特定的属性值。

<Room1>
            <Node Name='Scene1' Text='Morning'/>
            <Node Name='Scene2' Text='Leaving'/>
            <Node Name='Scene3' Text='Morning'/>
            <Node Name='Scene4' Text='Entertainment'/>
            <Node Name='Scene5' Text='Party'/>
            <Node Name='Scene6' Text='s6'/>
            <Node Name='Scene7' Text='Watch TV'/>
            <Node Name='Scene8' Text='Watch Movie'/>
            <Node Name='Scene9' Text='TV on Screen'/>
            <Node Name='Scene10' Text='Movie on Screen'/>
            <Node Name='Scene11' Text='Leaving Room'/>
</Room1>

我想获取属性 NameText 的值。以下代码是我尝试过的,

 $.ajax({
            method : "GET",
            url    :  "controller/Controller.php",
            data   : "myData=Room1",
            success:function(response){
                    var xml = response;

                    $(xml).find('Room1').each(function(){
                        $(this).find('Node').each(function(){
                            console.log($(this).attr('Name'));
                        });
                    });
                }
        });

提前致谢

【问题讨论】:

    标签: jquery xml ajax xml-parsing


    【解决方案1】:

    我建议你将整个xml转换成json,然后你可以像在jquery中使用对象一样使用json。

    jQuery plugin for serializing XML to JSON

    例如,要获取名称和文本属性,您要做的就是:

    $.each(jsonObject, function(index) { console.log($(this).name) }

    【讨论】:

    • 我以前尝试过这种方式,但我还没有找到这么好的插件来做到这一点。谢谢 Neeraj,它对我有用。
    猜你喜欢
    • 2011-12-06
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 2012-04-14
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多