【问题标题】:Parse nested xml of recursive dir list with jQuery使用jQuery解析递归目录列表的嵌套xml
【发布时间】:2013-03-21 03:25:21
【问题描述】:

我有基于 xml 的递归目录列表。例如,我想从特定目录获取文件列表。通过 XML,我应该只获取 img2.gif 和 img3.gif 和 img6.gif。但是脚本还返回实际上在子目录中的 img4 和 img5,我不想处理子目录. 目标是从请求的目录中获取文件并忽略嵌套的子目录。 一种方法是将 xml 结构从嵌套更改为正常,但我不想要那样。 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

【问题讨论】:

    标签: jquery xml parsing recursion nested


    【解决方案1】:

    仅查找具有children()find(' &gt; file') 或具有上下文$(' &gt; file', this) 等的直接子代,就像find() 查找所有 个后代,甚至是嵌套在下一个目录:

    $(xml).find('directory').each(function(){
         if($(this).attr('name')==path) {
             $(this).children('file').each(function(){
                 var list = $(this).attr('name');
                 alert(list);
             });
         }
    });
    

    【讨论】:

    • find() 发现所有descendents 是更好的解释,因为children 只被认为是第一级
    • 谢谢@adeneo。这就是诀窍。有没有一种方法/语法可以直接到达带有名称的目录,所以我不必 .find('directory').each(function() ?我想避免迭代。
    • $('directory[name="path"] &gt; file', xml).each(function() { ... });
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    相关资源
    最近更新 更多