2012-06-15 125 views
1

我有一个XML文件,如下所示。我如何使用Jquery读取所有元素。请注意,我不知道孩子元素名称处理文件如何使用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 
      }); 

} 
+1

会有独生子女,或孩子的孩子吗?你只想要孩子吗? –

+0

的问题是,这XM L文件正在动态更新,并且在处理文件时我不知道孩子的名字。所以我不能通过他们的名字来访问节点。 – Duleendra

+0

@shashi 这是固定的,甚至这个变化呢? – swapnesh

回答

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

1

这对我来说工作得很好:

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

$(data).children(); 

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

然后可以使用.nodeName获得标签的名称:

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

谢谢马修,这也适用于我。 – Duleendra

0

使用代码下面以粗体显示解析XML

功能解析(文件){ 的$(document)的每个子元素。找到(“技能”)。每个(函数(I,E){

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

     }); 
相关问题