How to parse XML data inside column in javascript?

1.2k views Asked by At

I have a XML data in this format:

<data>
<item type='String'>ABC</item>
<item type='Date'>
<Year>2015</Year>
<Month>May</Month>
<Day>24</Day>
</item>
</data>

I am parsing in this format:

var obj = someVariable.record[0].column[0].getText(); //obj

How can I parse the date 2015/May/24?

1

There are 1 answers

2
08Dc91wk On BEST ANSWER

In pure JavaScript you can do this as follows:

var xmlv = document.getElementsByTagName("data")[0];
var date = xmlv.querySelector('item[type="date"]');
var year = date.querySelector('Year').innerHTML;
var month = date.querySelector('Month').innerHTML;
var day = date.querySelector('Day').innerHTML;

var parsedDate = year + '/' + month + '/' + day;

Note that this uses the querySelector function which will not work in older browsers but will be fine in IE8+.

Pure JS version (as above) https://jsfiddle.net/n0xamj6L/

jQuery version (neater and more compatible) https://jsfiddle.net/t4pr8oyu/