0

I have xml based recursive dir list. I want to get file list from specific directory for example .By XML I should get only img2.gif and img3.gif and img6.gif .But script also returns img4 and img5 which are actually in sub dir and i dont want to process subdirs. Objective is to get files from requested dir and ignore nested sub dirs. One way is to change xml structure from nested to normal but i dont want that. XML

<directory name=".">
   <file name="img1.gif" />
   <directory name="images">
      <file name="images/img2.gif" /> 
      <file name="images/img3.gif" /> 
      <directory name="images/delta">
         <file name="images/delta/img4.gif" /> 
         <file name="images/delta/img5.gif" /> 
      </directory>
      <file name="images/img6.gif" /> 
   </directory>
</directory>

JAVASCRIPT

function parse_files(path) {
    $.ajax({
        type: "GET",
        url: "list.xml",
        dataType: "xml",
        success: function(xml) {

            $(xml).find('directory').each(function(){
                if($(this).attr('name')==path) {

                    $(this).find('file').each(function(){
                        var list = $(this).attr('name');
                        alert(list);
                    });
                 }
            });
        }

    });
}

parse_files("images");
// returns img2,img3,img4,img5,img6
// should return img2,img3,img6

1 Answer 1

1

Find only direct children with children(), or find(' > file') or with context $(' > file', this) etc, as just find() finds all descendents, even the ones that are nested further down in the next directory :

$(xml).find('directory').each(function(){
     if($(this).attr('name')==path) {
         $(this).children('file').each(function(){
             var list = $(this).attr('name');
             alert(list);
         });
     }
});
Sign up to request clarification or add additional context in comments.

3 Comments

find() finds all descendents is even better explanation since children are only considered to be first level down
Thank you @adeneo.That does the trick. Is there a way/ syntax that i can reach directory with name directly so I dont have to .find('directory').each(function() ? I want to avoid iterate.
$('directory[name="path"] > file', xml).each(function() { ... });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.