Upgrade to ExtJS 4.0.1 - Released 05/18/2011
[extjs.git] / src / data / writer / Xml.js
1 /**
2  * @author Ed Spencer
3  * @class Ext.data.writer.Xml
4  * @extends Ext.data.writer.Writer
5
6 This class is used to write {@link Ext.data.Model} data to the server in an XML format.
7 The {@link #documentRoot} property is used to specify the root element in the XML document.
8 The {@link #record} option is used to specify the element name for each record that will make
9 up the XML document.
10
11  * @markdown
12  */
13 Ext.define('Ext.data.writer.Xml', {
14     
15     /* Begin Definitions */
16     
17     extend: 'Ext.data.writer.Writer',
18     alternateClassName: 'Ext.data.XmlWriter',
19     
20     alias: 'writer.xml',
21     
22     /* End Definitions */
23     
24     /**
25      * @cfg {String} documentRoot The name of the root element of the document. Defaults to <tt>'xmlData'</tt>.
26      * If there is more than 1 record and the root is not specified, the default document root will still be used
27      * to ensure a valid XML document is created.
28      */
29     documentRoot: 'xmlData',
30     
31     /**
32      * @cfg {String} defaultDocumentRoot The root to be used if {@link #documentRoot} is empty and a root is required
33      * to form a valid XML document.
34      */
35     defaultDocumentRoot: 'xmlData',
36
37     /**
38      * @cfg {String} header A header to use in the XML document (such as setting the encoding or version).
39      * Defaults to <tt>''</tt>.
40      */
41     header: '',
42
43     /**
44      * @cfg {String} record The name of the node to use for each record. Defaults to <tt>'record'</tt>.
45      */
46     record: 'record',
47
48     //inherit docs
49     writeRecords: function(request, data) {
50         var me = this,
51             xml = [],
52             i = 0,
53             len = data.length,
54             root = me.documentRoot,
55             record = me.record,
56             needsRoot = data.length !== 1,
57             item,
58             key;
59             
60         // may not exist
61         xml.push(me.header || '');
62         
63         if (!root && needsRoot) {
64             root = me.defaultDocumentRoot;
65         }
66         
67         if (root) {
68             xml.push('<', root, '>');
69         }
70             
71         for (; i < len; ++i) {
72             item = data[i];
73             xml.push('<', record, '>');
74             for (key in item) {
75                 if (item.hasOwnProperty(key)) {
76                     xml.push('<', key, '>', item[key], '</', key, '>');
77                 }
78             }
79             xml.push('</', record, '>');
80         }
81         
82         if (root) {
83             xml.push('</', root, '>');
84         }
85             
86         request.xmlData = xml.join('');
87         return request;
88     }
89 });