How to convert (or serialize) a javascript data object (or model) to xml using ExtJs

  • How to convert this instance to XML?

I am working with ExtJs 4.2. I have an instance of an ExtJs model.

  1. How do I convert this to XML?

I have an anonymous JavaScript object (with several properties).

I am not sure that the answers to both of them are the same. XML will be sent as the body for the POST operation against a third-party web service.

+2
javascript xml extjs extjs4
source share
4 answers

Converting JSON to XML in JavaScript is blasphemy!

But if I had to do this, I would use: http://code.google.com/p/x2js/

+6
source share

I have not used this myself, but it seems like a good solution for anyone who makes a foreground / background agnostic approach.

https://github.com/michaelkourlas/node-js2xmlparser

+3
source share

I wrote the following function to make this work. Works very well when collections (arrays) inside your object have the suffix "s" (as the plural for their contents).

function serializeNestedNodeXML(xmlDoc, parentNode, newNodeName, obj) { if (Array.isArray(obj)) { var xmlArrayNode = xmlDoc.createElement(newNodeName); parentNode.appendChild(xmlArrayNode); obj.forEach(function (e) { serializeNestedNodeXML(xmlDoc, xmlArrayNode, newNodeName.substring(0, newNodeName.length - 1), e) }); return; // Do not process array properties } else if (obj) { var objType = typeof obj; switch (objType) { case 'string': case 'number': case 'boolean': parentNode.setAttribute(newNodeName, obj) break; case 'object': var xmlProp = xmlDoc.createElement(newNodeName); parentNode.appendChild(xmlProp); for (var prop in obj) { serializeNestedNodeXML(xmlDoc, xmlProp, prop, obj[prop]); } break; } } } 

And I called it this way (as a function of the serialized class itself):

 this.serializeToXML = function () { var xmlDoc = document.implementation.createDocument(null, "YourXMLRootNodeName", null); serializeNestedNodeXML(xmlDoc, xmlDoc.documentElement, 'YourSerializedClassName', this); var serializer = new XMLSerializer(); return serializer.serializeToString(xmlDoc); } 

But after an hour, I switched to JSON ...

+1
source share

For those of you who are interested in preserving the type of your JavaScript objects, think about this library that I wrote:

https://github.com/iconico/JavaScript-Serializer

0
source share

All Articles