zolio
zolio

Reputation: 2559

How to get the value embedded inside the xml tag using javascript?

I have an xml string like this:

<?xml version="1.0"?> 
<itemsPrice> 
    <setA> 
          <Category Code="A1">
                <price>30</price> 
          </Category> 
          <Category Code="A2">
                  <price>20</price> 
          </Category> 
     </setA>
    <setB> 
          <Category Code="A3"> 
                <price>70</price> 
           </Category> 
          <Category Code="A4"> 
                <price>80</price> 
          </Category> 
    </setB> 
</itemsPrice>

How do I get the values of the attribute "Code" in a javascript variable or array? What I want is like: A1, A2, A3, A4 preferably in an array. Or if it can be obtained inside an "each" function that is good too. How do I go about in Javascript for this?

Here is what I tried:

var xml=dataString;  // above xml string
xmlDoc = $.parseXML( xml );
$xml = $( xmlDoc );
$code = $xml.find("Category");
alert($code.text());  // gives me the values 30 20 70 80
                      // I want to get the values A1 A2 A3 A4

Upvotes: 0

Views: 671

Answers (3)

Ravi Kumar
Ravi Kumar

Reputation: 226

This should help you

$xml.find('Category').each(function(){
   alert($(this).attr('Code'));
});

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

Try this

var arr = [];
$code = $xml.find("Category");

$.each( $code , function(){
    arr.push( $(this).attr('Code'));
});

console.log( arr);  // Will have the code attributes

Upvotes: 1

Jacob George
Jacob George

Reputation: 2627

You can get all the Codes in an array using the following script

codeArray = []
$($($.parseXML(dataString)).find('Category')).each(function(){ codeArray.push($(this).attr('Code'))})

codeArray will be ["A1", "A2", "A3", "A4"]

Upvotes: 1

Related Questions