【问题标题】:How to read all the child elements of an element using Jquery如何使用 Jquery 读取元素的所有子元素
【发布时间】:2012-06-15 10:34:55
【问题描述】:

我有一个如下的 XML 文件。如何使用 Jquery 读取所有元素。请注意,我在处理文件时不知道子元素名称

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

}

【问题讨论】:

  • 只有孩子还是孩子的孩子?你只想要孩子吗?
  • 问题是,这个 XML 文件是动态更新的,在处理文件时我不知道孩子的名字。所以我不能通过他们的名字访问节点。
  • @shashi 这是固定的还是这个也改变了???

标签: jquery xml


【解决方案1】:

这对我来说很好用:

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

$(data).children();

这为您提供了一个 jQuery 元素数组。

然后您可以使用.nodeName 来获取标签的名称:

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

【讨论】:

    【解决方案2】:

    使用此代码并根据您的要求进行编辑:

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

    【讨论】:

      【解决方案3】:

      您可以选择根节点,然后遍历子集合。如果您期望更多级别的孩子,请递归执行

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

      您可以选择您的根并调用该函数

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

      我将它作为 $ 的扩展只是因为它是节点操作/遍历。如果它是您在项目中经常使用的东西,我更愿意在其余的操作/遍历逻辑(即 jQuery)中找到它。 (扩展 jQuery 存在名称冲突等问题)

      【讨论】:

        【解决方案4】:

        使用下面的粗体代码解析XML的每个子元素

        函数解析(文档){ $(document).find("技能").each(function(i,e){

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-05-11
          • 1970-01-01
          • 2022-01-11
          • 1970-01-01
          • 2021-12-25
          • 1970-01-01
          • 2019-08-20
          • 2011-01-25
          相关资源
          最近更新 更多