1

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!

3
  • 1
    Your output doesn't seem to match your array. What is the exact output you're looking for? What is param1 used for and how do you come up with the <fname> tag? Commented Jun 3, 2011 at 14:50
  • also unless you arent in control of php page youre sending to, it makes more sense to just send the data as JSON or standard form data and then build the xml on the php side. Commented Jun 3, 2011 at 14:53
  • <fname> tag is a standard I devised. So, I expect the xml stuff to look like this- <log> <fname>fname1</fname> <params> <param>param1</param> <param>param2</param> </params> </log> <log> <fname>fname2</fname> ..... Commented Jun 3, 2011 at 14:57

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Based on your latest comments you would simply change the inner for loop to do something like xmlNode += "<param>" + arr[node][i] + "</param>"
Thanks Colin. Worked perfectly for me!!
would there be any parsing errors if there is chars like "&" in between the nodes?
1

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.

Comments

0

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

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.