简体   繁体   中英

Search for element in XML file using jQuery

I have an XML file structured like this:

<movies>
    <movie>
        <title>A title</title>
        <year>2016</year>
    <boxoffice>18 million</boxoffice>
    </movie>
    <movie>
        <title>Second title</title>
        <year>2010</year>
        <boxoffice>10 million</boxoffice>
    </movie>
<movies>

I want to find all movies after year 2015 and show it in a table using jquery. I get the xml using:

function getx() {
            var x = $.ajax({
                url:      movies.xml,
                datatype: "xml",
                async:    false
            });
            return x.responseXML;
        }

and go though it using:

function find(year){
            var x = getx();
            $(x).find("year").each(function() {
                if (Number($(this).text()) > Number(year) {
                    $(document.getElementById("results")).append("<tr><td>" + $(this).text() + "</td></tr>");
                }
            });
        }

This returns creates a table row containing 2016. How could I modify this to search for one element and once found return all elements from the collection it belongs to? (I want to get a table row with title, year and boxoffice)

First: using an ajax call as sync is an issue, I suggest you to use a callback .

Second: in order to convert an xml to a jQuery object you can use jQuery.parseXML( data ) . After the conversion you can use .filter() and .each() for selecting the elements you need and append them to the table.

In jquery the ID Selector (“#id”) is:

$('#results')

instead of:

$(document.getElementById("results"))

In order to get the siblings elements you can use: Node.nextSibling and Node.previousSibling or you can use the jQuery.prev() and jQuery.next() .

The snippet:

 var xml = '<movies>\\ <movie>\\ <title>A title</title>\\ <year>2016</year>\\ <boxoffice>18 million</boxoffice>\\ </movie>\\ <movie>\\ <title>Second title</title>\\ <year>2010</year>\\ <boxoffice>10 million</boxoffice>\\ </movie>\\ </movies>'; var xmlDoc = $.parseXML( xml ); var jqXml = $(xmlDoc).find('year').filter((idx, ele) => {return +ele.textContent > 2015;}); jqXml.each(function(idx, ele) { $('#results').append("<tr><td>" + ele.previousSibling.textContent + "</td><td>" + ele.textContent + "</td><td>" + ele.nextSibling.textContent + "</td></tr>"); }) 
 td { border: 1px solid; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="results"> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM