Get value of any attribute from XML data in JavaScript?

Community Alums
Not applicable

Hi Experts,

I have requirement where I need to fetch the value from the XML, 


Below is the XMl
which I'm storing in one variable.


var xml = <?xml version='1.0' encoding='UTF-8'?><tsResponse xmlns="http://tableau.com/api" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tableau.com/api https://help.tableau.com/samples/en-us/rest_api/ts-api_3_14.xsd"><credentials token="gCosMMH6RUOYmar3dWwclA|dvfWAm9uul8ZkZjLpsk8X58r0CbZquoT" estimatedTimeToExpiration="362:21:46"><site id="8d919619-4390-46cb-9a9f-fdbe9b5e3fd7" contentUrl="Confirmation"/><user id="82d693e2-ab5a-49dd-bc11-d8b14f412c2b"/></credentials></tsResponse>

From the above XML I wanted to fetch and store the "credentials token" and "site id" values. using javascript.

Kindly help me on solving this.

Thanks,
Chaithanya

1 ACCEPTED SOLUTION

Dharmaraj Binna
Tera Guru

Hi Chaithanya,

Please refer to the below code as a solution to your question:

var token= xml.toString().split('credentials token="')[1].split('" estimated')[0];
var id = xml.toString().split('site id="')[1].split('" contentUrl')[0];
 
Below is the screenshot of the output of the code.
 

DharmarajBinna_0-1669821461035.png

Please mark the answer as correct, If I answered your query. It will be helpful for others who are looking for similar questions.

Regards,

Dharmaraj

View solution in original post

1 REPLY 1

Dharmaraj Binna
Tera Guru

Hi Chaithanya,

Please refer to the below code as a solution to your question:

var token= xml.toString().split('credentials token="')[1].split('" estimated')[0];
var id = xml.toString().split('site id="')[1].split('" contentUrl')[0];
 
Below is the screenshot of the output of the code.
 

DharmarajBinna_0-1669821461035.png

Please mark the answer as correct, If I answered your query. It will be helpful for others who are looking for similar questions.

Regards,

Dharmaraj