2011-06-03 31 views
1

我是JavaScript新手。我有一個我想解析的多維數組,並轉儲出xml標籤。例如,該陣列是我想要傾倒了XML標籤喜歡 -在Javascript中的循環中創建(xml)字符串

<fname>fname1</fname> 

一旦做到這一點

類型的
arr["fname1"][2] = param1 ; 

,我的最終目標是發送使用jQuery XML標記的該字符串。 ajax(),像這樣

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

我該如何去做這件事?請指教。謝謝!

+1

你的輸出看起來不符合你的數組。您要查找的確切輸出是什麼?什麼是'param1'用來做什麼,你怎麼想到''標籤? – 2011-06-03 14:50:45

+0

也除非你不控制你的PHP頁面發送到,更有意義的是發送數據作爲JSON或標準格式的數據,然後在PHP端建立XML。 – prodigitalson 2011-06-03 14:53:42

+0

標籤是我設計的標準。於是,我想到了XML的東西看起來像這 - fname1 參數1 參數2 fname2 ..... – piscianemperor 2011-06-03 14:57:31

回答

2

根據你的二維數組的複雜性,最簡單的事情是循環它並追加到一個字符串。例如

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>"; 
} 

這將使你像

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

如果陣列應該生成你可能要捎什麼是這裏所描述的線的方法更復雜的XML文檔/結構:

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

希望這會有所幫助。

+0

根據您的最新評論你會簡單地改變內循環做類似 'xmlNode + =「」+ ar r [node] [i] +「」' – Colin 2011-06-03 15:10:57

+0

謝謝科林。爲我完美工作! – piscianemperor 2011-06-03 17:05:24

+0

如果在節點之間有像「&」這樣的字符,會不會有任何解析錯誤? – 2015-02-05 17:44:59

0

你可以這樣做:

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

然後你就可以添加你喜歡的任何數據使用jQuery方法Append(你要發送的一個):

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

還有其他屬性處理數據。你也可以使用jquery選擇器來選擇特定的標籤,並操縱其內容。然後,您可以發送的數據是這樣的:

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

要獲得服務器端的數據,你必須得到一個方式來獲得原始post字符串,而是採用了類似字典的結構。使用Django,你可以這樣做。

我在應用程序中使用了這種方法,而且效果很好。

0

使用給定的信息,您可以執行以下操作(儘管我寧願發送數據(JSON))。這是柯林斯的解決方案(只有一個迴路,較小的字符串連接)

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

「優化」版本,我想我可能需要稍後,所以回答你的問題我已經構造一個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從谷歌地圖見a working example here(因爲它似乎是足夠複雜的對象)。