2013-08-27 108 views
0

我試圖在搜索子元素時返回父元素,然後顯示並行子元素的文本。jQuery XML解析 - 返回子元素的父元素

XML:

<store> 
    <shelf> 
     <book> 
      <name>Book_1</name> 
      <id>1</id> 
     </book> 
     <book> 
      <name>Book_2</name> 
      <id>2</id> 
     </book> 
     <book> 
      <name>Book_1</name> 
      <id>3</id> 
     </book> 
    </shelf> 
</store> 

的jQuery:

$(document).ready(function(){ 
    $.ajax({ 
     type: "GET", 
     url: "xml_file.xml", 
     dataType: "xml", 
     success: parseXml 
    }); 
}); 

function parseXml(xml){ 

    var books = $(xml).find('name').filter(function() { 
     return $(this).text() === 'Book_1'; 
    }).parent(); 

    for(i=0; i<books.length; i++){ 
     $('#results').text(
      (books[i]).find('id').text() 
     ); 
    } 
} 

HTML:

<div id="results"></div> 

所以基本上,如果我搜索了 「名」 與具有文本 「書」,我想收回2本書。比我想要顯示每本書到ID =「結果」的div。任何幫助,將不勝感激。謝謝!

+0

則可以將XML一些地方或給示例XML使用的網址... –

回答

0

你的XML是無效的,你少根節點,並</aid>應該</id>

<shelf> 
    <book> 
     <name>Book_1</name> 
     <id>1</id> 
    </book> 
    <book> 
     <name>Book_2</name> 
     <id>2</id> 
    </book> 
    <book> 
     <name>Book_1</name> 
     <id>3</id> 
    </book> 
</shelf> 

而且你錯過了在praseXml一個$和使用的.text將在寫入所有之前的值

function parseXml(xml){ 

    var books = $(xml).find('name').filter(function() { 
     return $(this).text() === 'Book_1'; 
    }).parent(); 

    for(i=0; i<books.length; i++){ 
     $('#results').append(
      $(books[i]).find('id').text() 
     ); 
    } 
} 

http://jsfiddle.net/uq9cW/

+0

我更新了原來的問題示例XML。這很好,謝謝! –

0

設置你的XML成brev一個局部變量性。

var $xml = $("<books><book><name>Book_1</name><id>1</aid></book><book><name>Book_2</name><id>2</aid></book><book> <name>Book_1</name><id>3</aid></book></books>") 

var searchString = "Book_1"; 
var matchedBooks = $xml 
    .children('book') /* Get all the books */ 
    .children('name') /* And then the names. You could just get the names first, but this will allow you to exclude nodes not inside of a book element */ 
    .filter(function(i,v){ return $(v).text() == searchString; }) /* This excludes non matching names. */ 
    .parent('book'); /* Now we have 2 matching elements, on each, get the parent element */ 

/* Build the html then append to save DOM interaction speed tax */ 
var resultHtml = ""; 
$(matchedBooks).each(function(i, e){ 
    resultHtml += "<p>" + $(e).find('id').text() + "</p>"; 
}); 
$("#results").html(resultHtml); 

讓我知道這是否回答您的問題