Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize XML to JavaScript/TypeScript?

I get a XML structure that contains information about an Appointment.

My code:

function AppointmentCallback(appointment : any) {
}

I want to convert this in an object in JavaScript or TypeScript(preferred). In jQuery there's only the parseXML method which makes the opposite from what I need.

Is there any library that makes this possible?

Thanks in advance!

like image 856
diiiz_ Avatar asked Jul 10 '14 13:07

diiiz_


Video Answer


2 Answers

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));
});
like image 139
jjrv Avatar answered Sep 17 '22 15:09

jjrv


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-tools also 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

like image 35
Moriarty Avatar answered Sep 20 '22 15:09

Moriarty