How to deserialize XML to JavaScript/TypeScript?

大城市里の小女人 提交于 2019-12-20 20:29:31

问题


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!


回答1:


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));
});



回答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.




回答3:


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




回答4:


You can also use serializeXmlNode from JSONconvert

as follow: Jsonconvert(doc)



来源:https://stackoverflow.com/questions/24678534/how-to-deserialize-xml-to-javascript-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!