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