Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / data / reader / Xml.js
1 /**
2  * @author Ed Spencer
3  * @class Ext.data.reader.Xml
4  * @extends Ext.data.reader.Reader
5  * 
6  * <p>The XML Reader is used by a Proxy to read a server response that is sent back in XML format. This usually
7  * happens as a result of loading a Store - for example we might create something like this:</p>
8  * 
9 <pre><code>
10 Ext.define('User', {
11     extend: 'Ext.data.Model',
12     fields: ['id', 'name', 'email']
13 });
14
15 var store = new Ext.data.Store({
16     model: 'User',
17     proxy: {
18         type: 'ajax',
19         url : 'users.xml',
20         reader: {
21             type: 'xml',
22             record: 'user'
23         }
24     }
25 });
26 </code></pre>
27  * 
28  * <p>The example above creates a 'User' model. Models are explained in the {@link Ext.data.Model Model} docs if you're
29  * not already familiar with them.</p>
30  * 
31  * <p>We created the simplest type of XML Reader possible by simply telling our {@link Ext.data.Store Store}'s 
32  * {@link Ext.data.proxy.Proxy Proxy} that we want a XML Reader. The Store automatically passes the configured model to the
33  * Store, so it is as if we passed this instead:
34  * 
35 <pre><code>
36 reader: {
37     type : 'xml',
38     model: 'User',
39     record: 'user'
40 }
41 </code></pre>
42  * 
43  * <p>The reader we set up is ready to read data from our server - at the moment it will accept a response like this:</p>
44  *
45 <pre><code>
46 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
47 &lt;user&gt;
48     &lt;id&gt;1&lt;/id&gt;
49     &lt;name&gt;Ed Spencer&lt;/name&gt;
50     &lt;email&gt;ed@sencha.com&lt;/email&gt;
51 &lt;/user&gt;
52 &lt;user&gt;
53     &lt;id&gt;2&lt;/id&gt;
54     &lt;name&gt;Abe Elias&lt;/name&gt;
55     &lt;email&gt;abe@sencha.com&lt;/email&gt;
56 &lt;/user&gt;
57 </code></pre>
58  * 
59  * <p>The XML Reader uses the configured {@link #record} option to pull out the data for each record - in this case we
60  * set record to 'user', so each &lt;user&gt; above will be converted into a User model.</p>
61  * 
62  * <p><u>Reading other XML formats</u></p>
63  * 
64  * <p>If you already have your XML format defined and it doesn't look quite like what we have above, you can usually
65  * pass XmlReader a couple of configuration options to make it parse your format. For example, we can use the 
66  * {@link #root} configuration to parse data that comes back like this:</p>
67  * 
68 <pre><code>
69 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
70 &lt;users&gt;
71     &lt;user&gt;
72         &lt;id&gt;1&lt;/id&gt;
73         &lt;name&gt;Ed Spencer&lt;/name&gt;
74         &lt;email&gt;ed@sencha.com&lt;/email&gt;
75     &lt;/user&gt;
76     &lt;user&gt;
77         &lt;id&gt;2&lt;/id&gt;
78         &lt;name&gt;Abe Elias&lt;/name&gt;
79         &lt;email&gt;abe@sencha.com&lt;/email&gt;
80     &lt;/user&gt;
81 &lt;/users&gt;
82 </code></pre>
83  * 
84  * <p>To parse this we just pass in a {@link #root} configuration that matches the 'users' above:</p>
85  * 
86 <pre><code>
87 reader: {
88     type  : 'xml',
89     root  : 'users',
90     record: 'user'
91 }
92 </code></pre>
93  * 
94  * <p>Note that XmlReader doesn't care whether your {@link #root} and {@link #record} elements are nested deep inside
95  * a larger structure, so a response like this will still work:
96  * 
97 <pre><code>
98 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
99 &lt;deeply&gt;
100     &lt;nested&gt;
101         &lt;xml&gt;
102             &lt;users&gt;
103                 &lt;user&gt;
104                     &lt;id&gt;1&lt;/id&gt;
105                     &lt;name&gt;Ed Spencer&lt;/name&gt;
106                     &lt;email&gt;ed@sencha.com&lt;/email&gt;
107                 &lt;/user&gt;
108                 &lt;user&gt;
109                     &lt;id&gt;2&lt;/id&gt;
110                     &lt;name&gt;Abe Elias&lt;/name&gt;
111                     &lt;email&gt;abe@sencha.com&lt;/email&gt;
112                 &lt;/user&gt;
113             &lt;/users&gt;
114         &lt;/xml&gt;
115     &lt;/nested&gt;
116 &lt;/deeply&gt;
117 </code></pre>
118  * 
119  * <p><u>Response metadata</u></p>
120  * 
121  * <p>The server can return additional data in its response, such as the {@link #totalProperty total number of records} 
122  * and the {@link #successProperty success status of the response}. These are typically included in the XML response
123  * like this:</p>
124  * 
125 <pre><code>
126 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
127 &lt;total&gt;100&lt;/total&gt;
128 &lt;success&gt;true&lt;/success&gt;
129 &lt;users&gt;
130     &lt;user&gt;
131         &lt;id&gt;1&lt;/id&gt;
132         &lt;name&gt;Ed Spencer&lt;/name&gt;
133         &lt;email&gt;ed@sencha.com&lt;/email&gt;
134     &lt;/user&gt;
135     &lt;user&gt;
136         &lt;id&gt;2&lt;/id&gt;
137         &lt;name&gt;Abe Elias&lt;/name&gt;
138         &lt;email&gt;abe@sencha.com&lt;/email&gt;
139     &lt;/user&gt;
140 &lt;/users&gt;
141 </code></pre>
142  * 
143  * <p>If these properties are present in the XML response they can be parsed out by the XmlReader and used by the
144  * Store that loaded it. We can set up the names of these properties by specifying a final pair of configuration 
145  * options:</p>
146  * 
147 <pre><code>
148 reader: {
149     type: 'xml',
150     root: 'users',
151     totalProperty  : 'total',
152     successProperty: 'success'
153 }
154 </code></pre>
155  * 
156  * <p>These final options are not necessary to make the Reader work, but can be useful when the server needs to report
157  * an error or if it needs to indicate that there is a lot of data available of which only a subset is currently being
158  * returned.</p>
159  * 
160  * <p><u>Response format</u></p>
161  * 
162  * <p><b>Note:</b> in order for the browser to parse a returned XML document, the Content-Type header in the HTTP 
163  * response must be set to "text/xml" or "application/xml". This is very important - the XmlReader will not
164  * work correctly otherwise.</p>
165  */
166 Ext.define('Ext.data.reader.Xml', {
167     extend: 'Ext.data.reader.Reader',
168     alternateClassName: 'Ext.data.XmlReader',
169     alias : 'reader.xml',
170     
171     /**
172      * @private
173      * Creates a function to return some particular key of data from a response. The totalProperty and
174      * successProperty are treated as special cases for type casting, everything else is just a simple selector.
175      * @param {String} key
176      * @return {Function}
177      */
178
179     /**
180      * @cfg {String} record The DomQuery path to the repeated element which contains record information.
181      */
182
183     createAccessor: function() {
184         var selectValue = function(expr, root){
185             var node = Ext.DomQuery.selectNode(expr, root),
186                 val;
187                 
188             
189             
190         };
191
192         return function(expr) {
193             var me = this;
194             
195             if (Ext.isEmpty(expr)) {
196                 return Ext.emptyFn;
197             }
198             
199             if (Ext.isFunction(expr)) {
200                 return expr;
201             }
202             
203             return function(root) {
204                 var node = Ext.DomQuery.selectNode(expr, root),
205                     val = me.getNodeValue(node);
206                     
207                 return Ext.isEmpty(val) ? null : val;
208             };
209         };
210     }(),
211     
212     getNodeValue: function(node) {
213         var val;
214         if (node && node.firstChild) {
215             val = node.firstChild.nodeValue;
216         }
217         return val || null;
218     },
219
220     //inherit docs
221     getResponseData: function(response) {
222         var xml = response.responseXML;
223
224         //<debug>
225         if (!xml) {
226             Ext.Error.raise({
227                 response: response,
228                 msg: 'XML data not found in the response'
229             });
230         }
231         //</debug>
232
233         return xml;
234     },
235
236     /**
237      * Normalizes the data object
238      * @param {Object} data The raw data object
239      * @return {Object} Returns the documentElement property of the data object if present, or the same object if not
240      */
241     getData: function(data) {
242         return data.documentElement || data;
243     },
244
245     /**
246      * @private
247      * Given an XML object, returns the Element that represents the root as configured by the Reader's meta data
248      * @param {Object} data The XML data object
249      * @return {Element} The root node element
250      */
251     getRoot: function(data) {
252         var nodeName = data.nodeName,
253             root     = this.root;
254         
255         if (!root || (nodeName && nodeName == root)) {
256             return data;
257         } else if (Ext.DomQuery.isXml(data)) {
258             // This fix ensures we have XML data
259             // Related to TreeStore calling getRoot with the root node, which isn't XML
260             // Probably should be resolved in TreeStore at some point
261             return Ext.DomQuery.selectNode(root, data);
262         }
263     },
264
265     /**
266      * @private
267      * We're just preparing the data for the superclass by pulling out the record nodes we want
268      * @param {Element} root The XML root node
269      * @return {Array} The records
270      */
271     extractData: function(root) {
272         var recordName = this.record;
273         
274         //<debug>
275         if (!recordName) {
276             Ext.Error.raise('Record is a required parameter');
277         }
278         //</debug>
279         
280         if (recordName != root.nodeName) {
281             root = Ext.DomQuery.select(recordName, root);
282         } else {
283             root = [root];
284         }
285         return this.callParent([root]);
286     },
287     
288     /**
289      * @private
290      * See Ext.data.reader.Reader's getAssociatedDataRoot docs
291      * @param {Mixed} data The raw data object
292      * @param {String} associationName The name of the association to get data for (uses associationKey if present)
293      * @return {Mixed} The root
294      */
295     getAssociatedDataRoot: function(data, associationName) {
296         return Ext.DomQuery.select(associationName, data)[0];
297     },
298
299     /**
300      * Parses an XML document and returns a ResultSet containing the model instances
301      * @param {Object} doc Parsed XML document
302      * @return {Ext.data.ResultSet} The parsed result set
303      */
304     readRecords: function(doc) {
305         //it's possible that we get passed an array here by associations. Make sure we strip that out (see Ext.data.reader.Reader#readAssociated)
306         if (Ext.isArray(doc)) {
307             doc = doc[0];
308         }
309         
310         /**
311          * DEPRECATED - will be removed in Ext JS 5.0. This is just a copy of this.rawData - use that instead
312          * @property xmlData
313          * @type Object
314          */
315         this.xmlData = doc;
316         return this.callParent([doc]);
317     }
318 });