jQuery parsing XML: get an element with a specific attribute

VansFannel picture VansFannel · Feb 10, 2012 · Viewed 71.4k times · Source

I'm developing an HTML5 application.

I want to parse an XML like this one:

<?xml version="1.0" encoding="utf-8" ?>
    <cards>
        ...
        <card id="3">
          <name lang="es"></name>
          <description lang="es"></description>
          <name lang="en"></name>
          <description lang="en"></description>
        </card>
        ...
    </cards>

I want to get the name and description that have attribute lang="en".

I start writing code, but I don't know how to finish it:

function loadCards(lang)
{
    $.ajax({
        type: "GET",
        url: 'data/english.xml',
        dataType: "xml",
        success:parseCardsXml
    });
}

function parseCardsXml(xml)
{
    $(xml).find('Card').each(function()
    {
        var id = $(this).attr('id');
        var name = $(this).find('name');
    }
}

By the way, loadCards function has an argument (or parameter) called lang.

How can I pass this argument to function parserCardsXml(xml)? How can I get name and description with a specific attribute?

Answer

Heretic Monkey picture Heretic Monkey · Feb 10, 2012

To answer the specific questions, "How can I pass this argument to function parserCardsXml(xml)?"

function loadCards(lang)
{
    $.ajax({
        type: "GET",
        url: 'data/english.xml',
        dataType: "xml",
        success: function (xml) { parseCardsXml(xml, lang); }
    });
}

And, "How can I get name and description with a specific attribute?"

function parseCardsXml(xml, lang)
{
    var $xml = $(xml),
        name = $xml.find('name[lang="' + lang + '"]').text(),
        desc = $xml.find('desc[lang="' + lang + '"]').text();
}