Я полагаю, что мне это может понадобиться позже, поэтому, чтобы ответить на ваш вопрос, я создал плагин jQuery, чтобы взять любой произвольный объект JavaScript и имя, которое вы хотели бы дать корневому узлу, и вернуть вам строку XML, представляющуюобъект.Плагин имеет встроенные комментарии:
(function($) {
$.extend({
/// <summary>
/// Build an XML structure from an object.
/// </summary>
/// <param name="obj">The object to transform to an XML structure.</param>
/// <param name="objName">The name of the XML node type.</param>
/// <param name="parentObj">(optional) The parent node of the XML structure.</param>
/// <returns>XML structure representing the object.</returns>
toXml: function(obj, objName, parentObj) {
// Use the supplied parent object or dimension a new root object
var $parent = parentObj ? parentObj : $("<" + objName + "></" + objName + ">");
// Determine if the object members do not have names
var blank = obj instanceof Array ? "<item></item>" : null;
// For each member of the object
$.each(obj, function(i, val) {
// Declare the next object with the appropriate naming convention
var $next = $(blank ? blank : "<" + i + "></" + i + ">");
// Add an index attribute to unnamed array members
if (blank) $next.attr("index", i);
if (typeof val === "object") {
// Recurse for object members
$next = $.toXml(val, i, $next);
} else {
// Otherwise set the text for leaf nodes
$next.text(val);
}
// Append this child node
$parent.append($next);
});
// Return the parent object with newly appended child nodes
return $parent;
},
/// <summary>
/// Build an XML string from an object.
/// </summary>
/// <param name="obj">The object to transform to an XML string.</param>
/// <param name="rootName">The name of the root XML node type.</param>
/// <returns>XML string representing the object.</returns>
toXmlString: function(obj, rootName) {
// Shell the XML object into a container and return its inner html
return $("<container></container>").append($.toXml(obj, rootName)).html();
}
});
})(jQuery);
ИСПОЛЬЗОВАНИЕ
$.toXmlString(myObj, "myObjName");
См. рабочий пример здесь с использованием образца объекта JSON GeocodeResponse от GoogleКарты (так как он казался объектом достаточной сложности).