user1850534
user1850534

Reputation:

jQuery XML parsing - Getting attribute values

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

Upvotes: 0

Views: 5813

Answers (1)

Neeraj
Neeraj

Reputation: 8532

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

Upvotes: 1

Related Questions