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!

2

1 Answer 1

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);

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.