- How do I convert that instance to XML?
I am working with ExtJs 4.2. I have an instance of an ExtJs model.
- How do I convert that to XML?
I have an anonymous JavaScript object (with a couple of properties).
I am not sure if the answers for both of the above is same. The XML will be sent as body to a POST operation against a third party web service.
- How do I convert that instance to XML?
I am working with ExtJs 4.2. I have an instance of an ExtJs model.
- How do I convert that to XML?
I have an anonymous JavaScript object (with a couple of properties).
I am not sure if the answers for both of the above is same. The XML will be sent as body to a POST operation against a third party web service.
Share Improve this question edited May 5, 2015 at 21:14 Ryan Gates 4,5397 gold badges52 silver badges92 bronze badges asked Nov 4, 2013 at 16:59 user203687user203687 7,24715 gold badges58 silver badges89 bronze badges 1- Ditch XML for the mor readable, lightweight data-interchange format, and de facto standard: JSON – Roko C. Buljan Commented Oct 23, 2023 at 18:35
3 Answers
Reset to default 7Converting JSON to XML in JavaScript is blasphemy!
But if I had to do it I would use: http://code.google./p/x2js/
I haven't used this myself, but it seems like a good solution for anyone doing for a front-/back-end agnostic approach.
https://github./michaelkourlas/node-js2xmlparser
I wrote the following function to do this job. Works pretty well when collections (arrays) inside your object are named with "s" suffix (as plurals for their content).
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 invoked 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 an hour later I moved to JSON...