问题
- 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.
回答1:
Converting JSON to XML in JavaScript is blasphemy!
But if I had to do it I would use: http://code.google.com/p/x2js/
回答2:
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.com/michaelkourlas/node-js2xmlparser
回答3:
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...
来源:https://stackoverflow.com/questions/19772917/how-to-convert-or-serialize-javascript-data-object-or-model-to-xml-using-ext