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