Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML string to JSON javascript

I have a xml string which i want to convert in JSON string

var txt = "<?xml version='1.0' encoding='UTF-8' ?>
                 <result>
                   <info>
                      <id>1</id>
                      <type>HL</type>
                      <ven>DEMOMA</ven>
                   </info>
                   <info>
                      <id>2</id>
                      <type>HL</type>
                      <ven>DEMOMB</ven>
                   </info>
               <result>";

i tried to initially convert it in DOM object using parser but it throws parsing error.

parser = new DOMParser();
xmlDoc = parser.parseFromString(txt,"text/xml");

i want my output json string like only by using Javascript

{"result":[{"id":"1","type":"HL","ven":"DEMOMA"},{"id":"2","type":"HL","ven":"DEMOMB"}]}
like image 217
Abhinav Parashar Avatar asked Apr 29 '16 04:04

Abhinav Parashar


1 Answers

Check out this https://github.com/metatribal/xmlToJSON

Its a very small and useful script. Usage is very easy.

Include the src

<script type="text/javascript" src="path/xmlToJSON.js"></script>

and enjoy! xmlToJSON is packaged as a simple module, so use it like this

testString = '<xml><a>It Works!</a></xml>';   // get some xml (string or document/node)
result = xmlToJSON.parseString(testString);   // parse

'result' is your JSON object.

like image 89
pramjeet Avatar answered Sep 26 '22 07:09

pramjeet