Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / src / data / XmlReader.js
1 /*!
2  * Ext JS Library 3.0.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.data.XmlReader
9  * @extends Ext.data.DataReader
10  * <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an XML document
11  * based on mappings in a provided {@link Ext.data.Record} constructor.</p>
12  * <p><b>Note</b>: that in order for the browser to parse a returned XML document, the Content-Type
13  * header in the HTTP response must be set to "text/xml" or "application/xml".</p>
14  * <p>Example code:</p>
15  * <pre><code>
16 var Employee = Ext.data.Record.create([
17    {name: 'name', mapping: 'name'},     // "mapping" property not needed if it is the same as "name"
18    {name: 'occupation'}                 // This field will use "occupation" as the mapping.
19 ]);
20 var myReader = new Ext.data.XmlReader({
21    totalRecords: "results", // The element which contains the total dataset size (optional)
22    record: "row",           // The repeated element which contains row information
23    id: "id"                 // The element within the row that provides an ID for the record (optional)
24 }, Employee);
25 </code></pre>
26  * <p>
27  * This would consume an XML file like this:
28  * <pre><code>
29 &lt;?xml version="1.0" encoding="UTF-8"?>
30 &lt;dataset>
31  &lt;results>2&lt;/results>
32  &lt;row>
33    &lt;id>1&lt;/id>
34    &lt;name>Bill&lt;/name>
35    &lt;occupation>Gardener&lt;/occupation>
36  &lt;/row>
37  &lt;row>
38    &lt;id>2&lt;/id>
39    &lt;name>Ben&lt;/name>
40    &lt;occupation>Horticulturalist&lt;/occupation>
41  &lt;/row>
42 &lt;/dataset>
43 </code></pre>
44  * @cfg {String} totalRecords The DomQuery path from which to retrieve the total number of records
45  * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
46  * paged from the remote server.
47  * @cfg {String} record The DomQuery path to the repeated element which contains record information.
48  * @cfg {String} success The DomQuery path to the success attribute used by forms.
49  * @cfg {String} idPath The DomQuery path relative from the record element to the element that contains
50  * a record identifier value.
51  * @constructor
52  * Create a new XmlReader.
53  * @param {Object} meta Metadata configuration options
54  * @param {Object} recordType Either an Array of field definition objects as passed to
55  * {@link Ext.data.Record#create}, or a Record constructor object created using {@link Ext.data.Record#create}.
56  */
57 Ext.data.XmlReader = function(meta, recordType){
58     meta = meta || {};
59     Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType || meta.fields);
60 };
61 Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, {
62     /**
63      * This method is only used by a DataProxy which has retrieved data from a remote server.
64      * @param {Object} response The XHR object which contains the parsed XML document.  The response is expected
65      * to contain a property called <tt>responseXML</tt> which refers to an XML document object.
66      * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
67      * a cache of Ext.data.Records.
68      */
69     read : function(response){
70         var doc = response.responseXML;
71         if(!doc) {
72             throw {message: "XmlReader.read: XML Document not available"};
73         }
74         return this.readRecords(doc);
75     },
76
77     /**
78      * Create a data block containing Ext.data.Records from an XML document.
79      * @param {Object} doc A parsed XML document.
80      * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
81      * a cache of Ext.data.Records.
82      */
83     readRecords : function(doc){
84         /**
85          * After any data loads/reads, the raw XML Document is available for further custom processing.
86          * @type XMLDocument
87          */
88         this.xmlData = doc;
89         var root = doc.documentElement || doc;
90         var q = Ext.DomQuery;
91         var recordType = this.recordType, fields = recordType.prototype.fields;
92         var sid = this.meta.idPath || this.meta.id;
93         var totalRecords = 0, success = true;
94         if(this.meta.totalRecords){
95             totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
96         }
97
98         if(this.meta.success){
99             var sv = q.selectValue(this.meta.success, root, true);
100             success = sv !== false && sv !== 'false';
101         }
102         var records = [];
103         var ns = q.select(this.meta.record, root);
104         for(var i = 0, len = ns.length; i < len; i++) {
105             var n = ns[i];
106             var values = {};
107             var id = sid ? q.selectValue(sid, n) : undefined;
108             for(var j = 0, jlen = fields.length; j < jlen; j++){
109                 var f = fields.items[j];
110                 var v = q.selectValue(Ext.value(f.mapping, f.name, true), n, f.defaultValue);
111                 v = f.convert(v, n);
112                 values[f.name] = v;
113             }
114             var record = new recordType(values, id);
115             record.node = n;
116             records[records.length] = record;
117         }
118
119         return {
120             success : success,
121             records : records,
122             totalRecords : totalRecords || records.length
123         };
124     },
125
126     // TODO: implement readResponse for XmlReader
127     readResponse : Ext.emptyFn
128 });