Duleendra
Duleendra

Reputation: 497

How to read all the child elements of an element using Jquery

I have a XML file as follows. How can I read all the elements using Jquery. Note that I do not know the child element names when processing the file

<Skills>
  <Programming>Yes</Programming>
  <Networking>No</Networking>
  <ProjectMangement>Yes</ProjectMangement>
</Skills>


$.ajax({
            url: 'application_form.xml', 
            dataType: "xml",
            success: parse,
            error: function(){alert("Error: Something went wrong");}
        });

function parse(document){
            $(document).find("Skills").each(function(i,e){

              //here i want to get the name of all the child elements
             });

}

Upvotes: 1

Views: 7379

Answers (4)

Pavan
Pavan

Reputation: 1

Use code in bold below to parse each child elements of XML

function parse(document){ $(document).find("Skills").each(function(i,e){

          //here i want to get the name of all the child elements
           **$(this).children().each(function () {                    
                 alert($(this).text());
             });**

         });

Upvotes: 0

Matthew Schinckel
Matthew Schinckel

Reputation: 35619

This worked fine for me:

var data = "<Skills><Programming>Yes</Programming><Networking>No</Networking><ProjectMangement>Yes</ProjectMangement></Skills>"

$(data).children();

This provides you with a jQuery array of elements.

You can then use .nodeName to get the tag's name:

$(data).children()[0].tagName;  // => "PROGRAMMING"

Upvotes: 1

Rune FS
Rune FS

Reputation: 21742

you can select the root node and then travers the child collection. If you are expecting more levels of children then do it recursively

$.fn.iterateChildren = function(fun){
    this.each(function(){
       if(fun(this)){
          this.iterateChildren(fun);
       }
    });
}

you can the select your root and call that function

$(document).find("Skills").iterateChildren(function(){
    //do some stuff
    //return true if you wish to keep iterating the siblings of the current node
    //return false if you wish to end the iteration (equivalent to break in a for loop
});

I've made it an extension to $ simply for the reason that it's node manipulation/traversal. If it's something you use often in you project I'd prefer to find it with the rest of the manipulation/traversal logic Ie jQuery. (There are issues with extending jQuery such as namecollisions)

Upvotes: 0

Sunny
Sunny

Reputation: 3295

Use this code and edit as per your requirement :

var xmlString = "<route><name>Lakeway</name><abrv>LAKE</abrv><eta><time>00:30</time>     <dest>MAIN</dest></eta></route>",
 xmlDoc = $.parseXML( xmlString ),
 $xml = $( xmlDoc ),
 $abrv = $xml.find( "abrv" ).text() == "LAKE" ? $xml.find( "abrv" ) : false;

 var time = $abrv.next().children("time").text();
 var dest = $abrv.next().children("dest").text();

 alert(time + " " + dest);

Upvotes: 0

Related Questions