简体   繁体   中英

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

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"]

Try this

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

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

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

This should help you

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

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