Parsing an XML document using jQuery, Is there an efficient method

1.4k Views Asked by At

Let's say for instance that I have the following XML doc, and I need to parse it using jQuery.

    <books>
        <book>
            <title>Gone with the Wind!</title>
        </book
        <book>
            <title>Lord of the Rings</title>
        </book>
        <book>
            <title>4 hour work week</title>
        </book
    </books>

In order to get the 'title' of the first book. I could use the following jQuery function.

    // let's assume xmldoc contains the above document.
    $(xmldoc).find("title").first().text();

This will give me the 'title' of the first book i.e. "Gone with the Wind!". Now, my question here is: Is this the efficient method to obtain the 'title' of the first book?

I am afraid, internally jQuery might be parsing the titles of all the books and then returning me the first(). I wonder, if am I wasting the CPU-cycles in parsing the books that I am not interested in?

Please suggest an alternative, if you can think of any. Thanks in advance!

PS: Please note that, I can't use browser's native javascript APIs, since the rest of the project uses jQuery for XML-parsing already.

1

There are 1 best solutions below

1
On

I can't speak to its efficiency (why not benchmark it?), but here is an alternate expression that uses just a single selector to achieve the same effect:

$( "book:first-child title", xmldoc ).text()

As @VincentMcNabb points out, jQuery tries to use browsers' built-in capabilities wherever possible.