2012-03-27 110 views
0

我正在處理涉及解析xml數據的JavaScript項目。我有以下結構的XML文件:用JQuery解析嵌套的xml

<?xml version="1.0" encoding="utf-8"?> 
<newsmodule> 
    <year name="2012"> 
     <news> 
     <date>Jan 01</date> 
     <title>title 1</title> 
     <info>info 1</info> 
    </news> 
    <news> 
     <date>Jan 02</date> 
     <title>title 2</title> 
     <info>info 2</info> 
    </news> 
</year> 
<year name="2011"> 
    <news> 
     <date>Jan 03</date> 
     <title>title 3</title> 
     <info>info 3</info> 
    </news> 
    <news> 
     <date>Jan 04</date> 
     <title>title 4</title> 
     <info>info 4</info> 
    </news> 
</year> 

我需要寫在每個陣列日期2012年一年。我使用了下面的代碼:

$(xml).find("year").each(function() { 

... 

$(xml).find("news").each(function() { 
    dates.push($(this).find("date").text()); 
    titles.push($(this).find("title").text()); 
    infos.push($(this).find("info").text()); 
}); 

而且顯而易見的原因是我有相同數組中所有年份的數據。

有沒有辦法讓這個工作?我可能不會更改xml文件。

+0

將XML轉換爲JSON的函數是否可以幫助您解決此問題? – 2012-03-27 17:27:45

回答

1

不要使用jQuery的DOM遍歷方法通過,這是非常依賴於瀏覽器使用parseXML的XML遍歷,此外,如果這正是你已經張貼的XML格式不正確,沒有結束</newsmodule>

var xml='<newsmodule> 
    <year name="2012"> 
     <news> 
     <date>Jan 01</date> 
     <title>title 1</title> 
     <info>info 1</info> 
    </news> 
    <news> 
     <date>Jan 02</date> 
     <title>title 2</title> 
     <info>info 2</info> 
    </news> 
</year> 
<year name="2011"><news> 
     <date>Jan 03</date> 
     <title>title 3</title> 
     <info>info 3</info> 
    </news> 
    <news> 
     <date>Jan 04</date> 
     <title>title 4</title> 
     <info>info 4</info> 
    </news> 
</year></newsmodule>'; 


    xmlDoc = $.parseXML(xml), 
    $xml = $(xmlDoc), 
    $title = $xml.find("year[name='2012']"); 

$("body").append($($title).find("date").text()); 

DEMO

+0

http://jsfiddle.net/HXLk4/24/ – Rafay 2012-03-27 17:26:44