Guest User

Untitled

a guest
Nov 17th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. function xml2json(xml) {
  2. try {
  3. var obj = {};
  4. if (xml.children.length > 0) {
  5. for (var i = 0; i < xml.children.length; i++) {
  6. var item = xml.children.item(i);
  7. var nodeName = item.nodeName;
  8.  
  9. if (typeof (obj[nodeName]) == "undefined") {
  10. obj[nodeName] = xml2json(item);
  11. } else {
  12. if (typeof (obj[nodeName].push) == "undefined") {
  13. var old = obj[nodeName];
  14.  
  15. obj[nodeName] = [];
  16. obj[nodeName].push(old);
  17. }
  18. obj[nodeName].push(xml2json(item));
  19. }
  20. }
  21. } else {
  22. obj = xml.textContent;
  23. }
  24. return obj;
  25. } catch (e) {
  26. console.log(e.message);
  27. }
  28. }
  29.  
  30. var xmlInText = '<?xml version="1.0" encoding="windows-1251" ?>' +
  31. '<CurrencyRates Name="Daily Exchange Rates" Date="16.11.2017">' +
  32. '<Currency ISOCode="USD">' +
  33. ' <Nominal>1</Nominal>' +
  34. ' <Value>69,7496</Value>' +
  35. ' </Currency>' +
  36. ' <Currency ISOCode="EUR">' +
  37. ' <Nominal>1</Nominal>' +
  38. ' <Value>82,5940</Value>' +
  39. ' </Currency>' +
  40. ' <Currency ISOCode="KZT">' +
  41. ' <Nominal>1</Nominal>' +
  42. ' <Value>0,2097</Value>' +
  43. ' </Currency>' +
  44. ' <Currency ISOCode="RUB">' +
  45. ' <Nominal>1</Nominal>' +
  46. ' <Value>1,1577</Value>' +
  47. ' </Currency>' +
  48. '</CurrencyRates>';
  49. var xml = new DOMParser().parseFromString(xmlInText,"text/xml");
  50. console.log(xml2json(xml))
Add Comment
Please, Sign In to add comment