如何使用Jquery读取元素的所有子元素

时间:2012-06-15 10:34:55

标签: jquery xml

我有一个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
             });

}

4 个答案:

答案 0 :(得分:1)

这对我来说很好:

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

$(data).children();

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

然后,您可以使用.nodeName获取代码的名称:

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

您可以选择根节点,然后遍历子集合。如果您期待更多级别的孩子,那么递归地进行

$.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有问题,比如namecollisions)

答案 3 :(得分:0)

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

函数解析(文档){             (文档)$ .find( “技能”)。每个(函数(I,E){

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

         });
相关问题