Deserializing XML in JavaScript with nearly no pain

We love to have software a little bit flexible. Therefore we have the need to store setup data in any place. Usuallly, in JavaScript, one would use JSON to store the data. Obviously, this is very easy to read for a JavaScript program.

But there are 2 disadvantages for this approach:

  • This format is mostly designed for JavaScript. If you have interaction with other languages, there is not a types ave way to exchange the data.
  • I do not know of any good support for editing that format in terms of context help or even type checking.

A diffrent approach is to use XML. Well, you think XML is hard to read in a JavaScript program. This is not fully true. There is a great library out there: Jsonix is your friend. We set up a XSD for our format and in visual studio (or other favorite editors), you get great support when editing the XML which is checked against the XSD and you get help out of the XSD itself. And if you like, you can write a small editor for your setup data and serialze the data into XML. This tool chain is fully supported by the visual studio.

So, what do you have to do in order to get XML support in your JavaScript project:

  1. Create an XSD for your data (write it by hand or get it generated from an exiting XML)
  2. Use Jsonix to create a so called mappingfile from the XSD
  3. Use the XSD in e.g. visual studio to generate an XML file, which contains data which is valid against the XSD
  4. In your JavaScript program, read your XML file via one of the build-in ways in Jsonix (as a web request or deserializing from string)
  5. Use the deserialized JavaScript object, which now holds your data JavaScript like

I prepared a littel stand-alone example of this szenario. You can find it here. Basically, the clsimplexsd.xsd was created. The provided batchjob createjsfilesfromxsd.bat was used to generate the mappings. The clsimple.xml file holds data generated with the help of visual studio and the XSD. The Jsonixexample.html file then demonstrates the usage of the generated mappingfile and the xml file to read the data. On the Jsonix pages, there is a lot of documentation on this.

Of course, in our CRM development, all the files including the XML are hosted as webresources.

PS: yes, XSD is cumbersome, but there is help on this.

 

,

No comments yet.

Leave a Reply