简体   繁体   中英

jQuery parsing XML: get an element with a specific attribute

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?

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();
}
var xml='<cards>\
        <card id="3">\
          <name lang="es"></name>\
          <description lang="es"></description>\
          <name lang="en"></name>\
          <description lang="en"></description>\
        </card></cards>';

and the jquery part

$(xml).find('Card').each(function(i,j)
    {           
       console.log($(j).attr("id"));
       console.log($(j).find("name").attr("lang"));

    });

http://www.jsfiddle.net/VZjmV/6/

$(xml).find('name[lang="en"], description[lang="en"]') should do the trick

Edit: More complete answer

$(xml).find('card').each(function () {
  var id, name, description;
  id          = $(this).attr('id'); // or just `this.id`
  name        = $(this).children('name[lang="en"]').text();
  description = $(this).children('description[lang="en"]').text();
  // do something with the id, name, and description
});

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