开发者

Creating a (xml) string in a loop in Javascript

I am new to Javascript. I have a multi-dimensional array that I want to parse through, and dump out xml tags. For example, the array is of type

arr["fname1"][2] = param1 ; 

I want to dump out xml tags like-

<fname>fname1<开发者_运维知识库/fname>

Once that is done, my final goal is to send this string of xml tags using jQuery.ajax(), like this

var xmlDocument = [create xml document];
$.ajax({
url: "page.php",
processData: false,
data: xmlDocument,
success: handleResponse
});

How do I go about doing this? Please advice. Thanks!


Depending on the complexity of your 2 dimensional array, the simplest thing would be to loop through it and append to a string. For example

function createXMLDocument(arr){
  var xmlDocument = "<myxmldoc>\n"

  for (node in arr) {
    var xmlNode = "\t<fname ";
    for (var i = 0; i < arr[node].length; i++){
      xmlNode += " attr" + i + "=\"" + arr[node][i] + "\" ";
    }
    xmlNode += ">" + node + "</fname>";
    xmlDocument += "\n" + xmlNode;
  }

  return xmlDocument + "\n</myxmldoc>";
}

This would give you something like

<myxmldoc>
  <fname attr0="param1" attr1="param2" ...>fname1</fname>
  <fname attr0="param1" attr1="param2" ...>fname2</fname>
  ...
</myxmldoc>

If your array should generate a more complex xml document / structure you may want to take an approach along the lines what is described here:

http://oreilly.com/pub/h/2127

Hope this helps.


You can do this:

var xmlData = $('<data></data>');

Then you can append whatever data you like (the one you want to send) using the jquery method append:

xmlData.append("<myParentTag></myParentTag>");

There are other properties to handle the data. You can also use jquery selectors to select specific tags, and manipulate its contents. Then, you can send the data like this:

$.post(
    "/my_url/", 
    xmlData.html(), 
    function(msg) {/* On success perform actions */;}
);

To get the data in the server side, you have to get a way to get the raw post string, instead of using a dictionary-like structure. Using Django, you are able to do so.

I used this approach in an app, and it worked great.


With the given informations you could do the following (although I would prefer sending the data as it is (JSON)). It is an "optimised" version of Colins solution (only one loop, lesser string concatenations)

var arr = {
        "fname1": [1, 2, 3, 4], 
        "fname2": [1, 2, 3, 4],
        "fname3": [1, 2, 3, 4],
        "fname4": [1, 2, 3, 4]
    },
    xml = [],
    tag = null;


for (tag in arr) {
    if (arr.hasOwnProperty(tag) == false) {
        xml.push("<fname>" + tag + "</fname>");
        xml.push("<params><param>" + obj[tag].join("</param><param>") + "/param></params>");
    }
}

console.log(xml.join(""))


I figure I might need this later, so to answer your question I've constructed a jQuery plugin to take any arbitrary JavaScript object and the name you'd like to give the root node and return to you an XML string representing the object. The plugin is commented inline:

(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);

USAGE

$.toXmlString(myObj, "myObjName");

See a working example here using a sample JSON GeocodeResponse object from Google Maps (since it seemed like an object of sufficient complexity).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜