Lukas
Lukas

Reputation: 7734

XML get data by element attr

Hi i have some problem with xml parsing. So - i want to read data from some xml tags by data. Can you help me? This is my code.

    <data>
        <element name="name">Zook</element>
        <element name="image">img/icons/01/zook.png</element>
    </data>

and jquery

$(this).find("element").each(function(){
    var name = $(this).attr("name");
    $("#div").html('<span>' + name + '</span>')
});

Upvotes: 0

Views: 238

Answers (5)

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 67021

$(xml).find("main_menu").each(function () {
    var name, image;

    $(this).find("element").each(function() {
        // make sure they default to what they originally were if null
        // since one <element> has name other has image
        name = ($(this).attr('name')) ? $(this).text() : name;
        image = ($(this).attr('image')) ? $(this).text() : image;
    });

    // Build the items once you've looped through the elements within a <data> section
    $("#carousel_items").append('<span>' + name + '</span><span>' + image + '</span>')
});

Upvotes: 0

ScampDoodle
ScampDoodle

Reputation: 296

This sample code will extract the data for you:

$.ajax({
   type: "GET",
   url: "path/to/your/xml.xml",
   dataType: "xml",
   success: function(xml){
   $(xml).find("element").each(function() {
          var name = $(this).find("name").text();
          var image = $(this).find("image").text();
          $("#div").html('<span>' + name + '</span>');
   });
});

You will need to restructure your xml though, as at present element has a dual meaning. Simplify this so that your data looks like this:

<data>
  <element>
    <image>path/to/img.ext</image>
    <name>Name</name>
  </element>
</data>

Hope this helps

Upvotes: 1

Lukas
Lukas

Reputation: 7734

$(xml).find("main_menu").each(function () {
    $(this).find("element").each(function(){
        var name = $(this).text();
        var image = $(this).text();

        $("#carousel_items").append('<span>' + name + '</span><span>' + image + '</span>')
    });
});

this is how my code looks like now

Upvotes: 0

AdityaParab
AdityaParab

Reputation: 7100

var name = $(this).text();

Should make your life easier

Upvotes: 0

Fahid Mohammad
Fahid Mohammad

Reputation: 930

Just go through this Link it explains everything you need :)

$(xml).find("element").each(function()
 {
   $("#output").append($(this).attr("name") + "<br />");
 });

Upvotes: 1

Related Questions