How to deserialize XML to JavaScript/TypeScript? How to deserialize XML to JavaScript/TypeScript? xml xml

How to deserialize XML to JavaScript/TypeScript?


cxml can parse XML into JSON and also fire handlers during parsing to process a file as it loads. You can compile .xsd schema files to TypeScript .d.ts definition files using cxsd. The parsed output will also be fully typed so an IDE like Atom or the tsc compiler can check that you're correctly handling the parsed JSON (element and attribute names and data types etc.)

Here's what using it looks like (more examples in Github):

import * as cxml from 'cxml';import * as example from 'cxml/test/xmlns/dir-example';var parser = new cxml.Parser();var result = parser.parse('<dir name="empty"></dir>', example.document);result.then((doc: example.document) => {    console.log(JSON.stringify(doc, null, 2));});


MDN has a good article on XML serialization and deserialisation in JavaScript, which covers all the options without having to resort to libraries such as jQuery.

Older versions of IE (pre-11) - and the current version of Opera Mini - have some limitations that may cause problems if you need to support them. Notably DOMParser.parseFromString is missing: Check this.

If you really do want to convert to JavaScript objects rather than work with a DOM, probably what you want to look at is JXON. Here's the way.

Note that if you want to recreate your XML document from objects at any point, I'd recommend you convert it to a DOM and work directly with the DOM nodes. That way, when you reserialize it, the ordering of nodes will be preserved. If you go down the plain old JavaScript object route, ordering will be lost.


Check out the cxsd library https://www.npmjs.com/package/cxsd it parses xsd to typescript. It has some odd dependencies. I had to do an npm install --global --production windows-build-toolsalso make sure cxsd.cmd is included the PATH it is a cli cxsd file.xsd it outputs a .d.ts file with the generated typescript