0

我试图在搜索子元素时返回父元素,然后显示并行子元素的文本。

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="results" 的 div 上。任何帮助,将不胜感激。谢谢!

4

2 回答 2

1

您的 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 中缺少 a 并且使用 .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/

于 2013-08-27T18:14:14.027 回答
0

为简洁起见,将您的 xml 设置为局部变量。

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

让我知道这是否回答了您的问题

于 2013-08-27T18:33:31.987 回答