jQuery XML parsing - Getting attribute values

雨燕双飞 提交于 2019-12-25 10:48:10

问题


I am getting this following xml response after sending requests through Ajax, so i want to parse this following xml data using jQuery to get the specific attribute values.

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

I want to get the values of attributes Name and Text. The following code is what i have tried,

 $.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'));
                        });
                    });
                }
        });

Thanks in advance


回答1:


I would suggest you convert the whole xml into json, and then you can use json as you use objects in jquery.

jQuery plugin for serializing XML to JSON

e.g to get to name and text attribute, all you would do is:

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



来源:https://stackoverflow.com/questions/18627702/jquery-xml-parsing-getting-attribute-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!