Search code examples
javascriptjqueryxmlparsexml

jquery parse xml for multiple tags


I want to get multiple tags from an XML document. I looked at this question which essentially gets sub-elements of one tag, whereas I want all the tags. Using the same example XML (replicated below):

var data = 
"<root>
    <instructions>Some ins text.</instructions>
    <options>
       <option>1.png</option>
       <option>2.png</option>
       <option>3.png</option>
       <option>4.png</option>
    </options>
    <noOfOptions>4</noOfOptions>
</root>";

How do I get the values for "instructions", "options" and "noOfOptions"?

I could just repeat the code three times like this:

xml = $.parseXML(data),
$data = $( xml ),
$options = $data.find("option"); // get all option nodes

xml = $.parseXML(data),
$data = $( xml ),
$instructions = $xml.find("instructions"); // get instructions

xml = $.parseXML(data),
$data = $( xml ),
$noOfOptions = $xml.find("noOfOptions"); // get noOfOptions

But that doesn't seem right. Is there a correct (and more efficient) way to do this? I think the .each function has something to do with it, but don't really understand how to use it.


Solution

  • var data = 
    "<root>\
        <instructions>Some ins text.</instructions>\
        <options>\
           <option>1.png</option>\
           <option>2.png</option>\
           <option>3.png</option>\
           <option>4.png</option>\
        </options>\
        <noOfOptions>4</noOfOptions>\
    </root>";
    
    
    var xml = $.parseXML(data);
    var $data = $( xml );
    
    var instructions = $data.find("instructions").text();
    var options = [];
    $data.find("option").each(function(){
      options.push($(this).text());
    });
    
    console.log("instructions: " + instructions);
    console.log("options: ", options);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>