3

Suppose to have an xml like this:

   <?xml version="1.0" encoding="UTF-8"?>
 <Langs>
<dirs>
  <string>uk-fr</string>
  <string>uk-it</string>
  <string>uk-pl</string>
  <string>uk-tr</string>
</dirs>
<langs>
  <Item key="af" value="Afrikaans" />
  <Item key="ar" value="Arabic" />
  <Item key="az" value="Azerbaijani" />
  <Item key="ba" value="Bashkir" />
  <Item key="be" value="Belarusian" />
 </langs>
</Langs>

How can I get an array that contains the key of each item? Using javascipt? An object as this:

  var array = [af,ar,az,ba,be]
7
  • You can use DOMParser and then work with the document it returns. (I'm not at a computer now so can't try it out and give an example.) Commented Jun 6, 2016 at 16:00
  • Also there is jQuery.parseXML. Commented Jun 6, 2016 at 16:01
  • @BlazeSahlzen But why use jQuery if you don't need it? Commented Jun 6, 2016 at 16:09
  • @gcampbell The DOMParser is an experimental feature and may not be supported everywhere. Commented Jun 6, 2016 at 16:23
  • 1
    @BlazeSahlzen stackoverflow.com/a/7951947/6303733, caniuse.com/#search=domparser, compare with jquery.com/browser-support Commented Jun 6, 2016 at 16:31

1 Answer 1

1

Sorry for the late reply.

Here's an example code on how to use jQuery.parseXML to solve the problem:

var xml_string = 'your xml string';

var output = $.parseXML(xml_string); // <-------- parsing using jQuery.parseXML

var array = []; // <----------------------------- array for storing the keys

// iterating over the elements where selector 'langs>Item' matches in the parsed XML
// and retrieving the key values and pushing them into the array
$('langs>Item', output).each(function(i, e) {
  array.push($(e).attr('key'));
});

// display the output
console.log(array);

Here's a fiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.