0

I have a remote Web service that returns to my JavaScript Web app the variable "DATA" defined in XML format.

An example of the data returned by a request would be:

<DATA><ID>1</ID><NAME>JOHN SMITH</NAME></DATA>

In JavaScript, how can I access the values of its attributes, i.e. the "1" as the ID and "JOHN SMITH" as the NAME?

For simplification,

(...)   

var DATA = <DATA><ID>1</ID><NAME>JOHN SMITH</NAME></DATA>;
var ID = ??; //HOW TO ACCESS THE VALUE OF ID IN DATA?
var NAME = ??; //HOW TO ACCESS THE VALUE OF NAME IN DATA?

(...)

Thank you!

Julia
  • 509
  • 1
  • 7
  • 19
  • [Please don't put tags in question titles](https://stackoverflow.com/help/tagging) – Liam Dec 05 '17 at 16:26
  • Possible duplicate of [Cross-Browser Javascript XML Parsing](https://stackoverflow.com/questions/7949752/cross-browser-javascript-xml-parsing) – Liam Dec 05 '17 at 16:27

1 Answers1

1

Use DomParser and querySelector

var xml = "<DATA><ID>1</ID><NAME>JOHN SMITH</NAME></DATA>";
var doc = new DOMParser().parseFromString(xml, "text/xml");

console.log(doc.querySelector( "ID" ).innerHTML);
console.log(doc.querySelector( "NAME" ).innerHTML);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94