2012-06-15 124 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()); 
      });** 

     }); 
相關問題