2

There are many examples on how to parse and read XML files, but so far, I've not found one with the Android resource format XML file:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="form_submit">Submit</string>
        <string name="form_abort">Cancel</string>
        <string name="form_reset">Clear</string>
    </resources>
  1. How do I read such an XML file into a Javascript variable?
  2. How do I read the values (Submit, Cancel, Clear) using their corresponding keys, (form_submit, form_abort, form_reset)?

Any help is appreciated. Thank you.

iSofia
  • 1,412
  • 2
  • 19
  • 36

1 Answers1

2

You could use DOMParser() and querySelectorAll()

var submit,abort,reset;
var text = '<resources><string name="form_submit">Submit</string><string name="form_abort">Cancel</string><string name="form_reset">Clear</string></resources>';

parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");

submit = xmlDoc.querySelectorAll("string[name='form_submit']")[0].innerHTML;
abort = xmlDoc.querySelectorAll("string[name='form_abort']")[0].innerHTML;
reset = xmlDoc.querySelectorAll("string[name='form_reset']")[0].innerHTML;
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
  • Wow! That's great. And simple too. Thank you so much. If the source XML is in a local file, what would be the best way to read it into a Javascript variable? – iSofia Mar 02 '18 at 20:40
  • There are browser security restrictions that usually prevent arbitrarily reading files from the filesystem, but there may be options depending how you expect the file to be selected i.e. `` or if your browser supports the File API: https://stackoverflow.com/questions/371875/local-file-access-with-javascript – Mads Hansen Mar 02 '18 at 22:05