Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
YUI.add('dataschema-xml', function (Y, NAME) {
2
 
3
/**
4
Provides a DataSchema implementation which can be used to work with XML data.
5
 
6
@module dataschema
7
@submodule dataschema-xml
8
**/
9
 
10
/**
11
Provides a DataSchema implementation which can be used to work with XML data.
12
 
13
See the `apply` method for usage.
14
 
15
@class DataSchema.XML
16
@extends DataSchema.Base
17
@static
18
**/
19
var Lang = Y.Lang,
20
 
21
    okNodeType = {
22
        1 : true,
23
        9 : true,
24
        11: true
25
    },
26
 
27
    SchemaXML;
28
 
29
SchemaXML = {
30
 
31
    ////////////////////////////////////////////////////////////////////////////
32
    //
33
    // DataSchema.XML static methods
34
    //
35
    ////////////////////////////////////////////////////////////////////////////
36
    /**
37
    Applies a schema to an XML data tree, returning a normalized object with
38
    results in the `results` property. Additional information can be parsed out
39
    of the XML for inclusion in the `meta` property of the response object.  If
40
    an error is encountered during processing, an `error` property will be
41
    added.
42
 
43
    Field data in the nodes captured by the XPath in _schema.resultListLocator_
44
    is extracted with the field identifiers described in _schema.resultFields_.
45
    Field identifiers are objects with the following properties:
46
 
47
      * `key`    : <strong>(required)</strong> The desired property name to use
48
            store the retrieved value in the result object.  If `locator` is
49
            not specified, `key` is also used as the XPath locator (String)
50
      * `locator`: The XPath locator to the node or attribute within each
51
            result node found by _schema.resultListLocator_ containing the
52
            desired field data (String)
53
      * `parser` : A function or the name of a function on `Y.Parsers` used
54
            to convert the input value into a normalized type.  Parser
55
            functions are passed the value as input and are expected to
56
            return a value.
57
      * `schema` : Used to retrieve nested field data into an array for
58
            assignment as the result field value.  This object follows the same
59
            conventions as _schema_.
60
 
61
    If no value parsing or nested parsing is needed, you can use XPath locators
62
    (strings) instead of field identifiers (objects) -- see example below.
63
 
64
    `response.results` will contain an array of objects with key:value pairs.
65
    The keys are the field identifier `key`s, and the values are the data
66
    values extracted from the nodes or attributes found by the field `locator`
67
    (or `key` fallback).
68
 
69
    To extract additional information from the XML, include an array of
70
    XPath locators in _schema.metaFields_.  The collected values will be
71
    stored in `response.meta` with the XPath locator as keys.
72
 
73
    @example
74
        var schema = {
75
                resultListLocator: '//produce/item',
76
                resultFields: [
77
                    {
78
                        locator: 'name',
79
                        key: 'name'
80
                    },
81
                    {
82
                        locator: 'color',
83
                        key: 'color',
84
                        parser: function (val) { return val.toUpperCase(); }
85
                    }
86
                ]
87
            };
88
 
89
        // Assumes data like
90
        // <inventory>
91
        //   <produce>
92
        //     <item><name>Banana</name><color>yellow</color></item>
93
        //     <item><name>Orange</name><color>orange</color></item>
94
        //     <item><name>Eggplant</name><color>purple</color></item>
95
        //   </produce>
96
        // </inventory>
97
 
98
        var response = Y.DataSchema.JSON.apply(schema, data);
99
 
100
        // response.results[0] is { name: "Banana", color: "YELLOW" }
101
 
102
    @method apply
103
    @param {Object} schema Schema to apply.  Supported configuration
104
        properties are:
105
      @param {String} [schema.resultListLocator] XPath locator for the
106
          XML nodes that contain the data to flatten into `response.results`
107
      @param {Array} [schema.resultFields] Field identifiers to
108
          locate/assign values in the response records. See above for
109
          details.
110
      @param {Array} [schema.metaFields] XPath locators to extract extra
111
          non-record related information from the XML data
112
    @param {XMLDocument} data XML data to parse
113
    @return {Object} An Object with properties `results` and `meta`
114
    @static
115
    **/
116
    apply: function(schema, data) {
117
        var xmldoc = data, // unnecessary variables
118
            data_out = { results: [], meta: {} };
119
 
120
        if (xmldoc && okNodeType[xmldoc.nodeType] && schema) {
121
            // Parse results data
122
            data_out = SchemaXML._parseResults(schema, xmldoc, data_out);
123
 
124
            // Parse meta data
125
            data_out = SchemaXML._parseMeta(schema.metaFields, xmldoc, data_out);
126
        } else {
127
            data_out.error = new Error("XML schema parse failure");
128
        }
129
 
130
        return data_out;
131
    },
132
 
133
    /**
134
     * Get an XPath-specified value for a given field from an XML node or document.
135
     *
136
     * @method _getLocationValue
137
     * @param field {String | Object} Field definition.
138
     * @param context {Object} XML node or document to search within.
139
     * @return {Object} Data value or null.
140
     * @static
141
     * @protected
142
     */
143
    _getLocationValue: function(field, context) {
144
        var locator = field.locator || field.key || field,
145
            xmldoc = context.ownerDocument || context,
146
            result, res, value = null;
147
 
148
        try {
149
            result = SchemaXML._getXPathResult(locator, context, xmldoc);
150
            while ((res = result.iterateNext())) {
151
                value = res.textContent || res.value || res.text || res.innerHTML || res.innerText || null;
152
            }
153
 
154
            // FIXME: Why defer to a method that is mixed into this object?
155
            // DSchema.Base is mixed into DSchema.XML (et al), so
156
            // DSchema.XML.parse(...) will work.  This supports the use case
157
            // where DSchema.Base.parse is changed, and that change is then
158
            // seen by all DSchema.* implementations, but does not support the
159
            // case where redefining DSchema.XML.parse changes behavior. In
160
            // fact, DSchema.XML.parse is never even called.
161
            return Y.DataSchema.Base.parse.call(this, value, field);
162
        } catch (e) {
163
        }
164
 
165
        return null;
166
    },
167
 
168
    /**
169
     * Fetches the XPath-specified result for a given location in an XML node
170
     * or document.
171
     *
172
     * @method _getXPathResult
173
     * @param locator {String} The XPath location.
174
     * @param context {Object} XML node or document to search within.
175
     * @param xmldoc {Object} XML document to resolve namespace.
176
     * @return {Object} Data collection or null.
177
     * @static
178
     * @protected
179
     */
180
    _getXPathResult: function(locator, context, xmldoc) {
181
        // Standards mode
182
        if (! Lang.isUndefined(xmldoc.evaluate)) {
183
            return xmldoc.evaluate(locator, context, xmldoc.createNSResolver(context.ownerDocument ? context.ownerDocument.documentElement : context.documentElement), 0, null);
184
 
185
        }
186
        // IE mode
187
        else {
188
            var values=[], locatorArray = locator.split(/\b\/\b/), i=0, l=locatorArray.length, location, subloc, m, isNth;
189
 
190
            // XPath is supported
191
            try {
192
                // this fixes the IE 5.5+ issue where childnode selectors begin at 0 instead of 1
193
                try {
194
                   xmldoc.setProperty("SelectionLanguage", "XPath");
195
                } catch (e) {}
196
 
197
                values = context.selectNodes(locator);
198
            }
199
            // Fallback for DOM nodes and fragments
200
            catch (e) {
201
                // Iterate over each locator piece
202
                for (; i<l && context; i++) {
203
                    location = locatorArray[i];
204
 
205
                    // grab nth child []
206
                    if ((location.indexOf("[") > -1) && (location.indexOf("]") > -1)) {
207
                        subloc = location.slice(location.indexOf("[")+1, location.indexOf("]"));
208
                        //XPath is 1-based while DOM is 0-based
209
                        subloc--;
210
                        context = context.children[subloc];
211
                        isNth = true;
212
                    }
213
                    // grab attribute value @
214
                    else if (location.indexOf("@") > -1) {
215
                        subloc = location.substr(location.indexOf("@"));
216
                        context = subloc ? context.getAttribute(subloc.replace('@', '')) : context;
217
                    }
218
                    // grab that last instance of tagName
219
                    else if (-1 < location.indexOf("//")) {
220
                        subloc = context.getElementsByTagName(location.substr(2));
221
                        context = subloc.length ? subloc[subloc.length - 1] : null;
222
                    }
223
                    // find the last matching location in children
224
                    else if (l != i + 1) {
225
                        for (m=context.childNodes.length-1; 0 <= m; m-=1) {
226
                            if (location === context.childNodes[m].tagName) {
227
                                context = context.childNodes[m];
228
                                m = -1;
229
                            }
230
                        }
231
                    }
232
                }
233
 
234
                if (context) {
235
                    // attribute
236
                    if (Lang.isString(context)) {
237
                        values[0] = {value: context};
238
                    }
239
                    // nth child
240
                    else if (isNth) {
241
                        values[0] = {value: context.innerHTML};
242
                    }
243
                    // all children
244
                    else {
245
                        values = Y.Array(context.childNodes, 0, true);
246
                    }
247
                }
248
            }
249
 
250
            // returning a mock-standard object for IE
251
            return {
252
                index: 0,
253
 
254
                iterateNext: function() {
255
                    if (this.index >= this.values.length) {return undefined;}
256
                    var result = this.values[this.index];
257
                    this.index += 1;
258
                    return result;
259
                },
260
 
261
                values: values
262
            };
263
        }
264
    },
265
 
266
    /**
267
     * Schema-parsed result field.
268
     *
269
     * @method _parseField
270
     * @param field {String | Object} Required. Field definition.
271
     * @param result {Object} Required. Schema parsed data object.
272
     * @param context {Object} Required. XML node or document to search within.
273
     * @static
274
     * @protected
275
     */
276
    _parseField: function(field, result, context) {
277
        var key = field.key || field,
278
            parsed;
279
 
280
        if (field.schema) {
281
            parsed = { results: [], meta: {} };
282
            parsed = SchemaXML._parseResults(field.schema, context, parsed);
283
 
284
            result[key] = parsed.results;
285
        } else {
286
            result[key] = SchemaXML._getLocationValue(field, context);
287
        }
288
    },
289
 
290
    /**
291
     * Parses results data according to schema
292
     *
293
     * @method _parseMeta
294
     * @param xmldoc_in {Object} XML document parse.
295
     * @param data_out {Object} In-progress schema-parsed data to update.
296
     * @return {Object} Schema-parsed data.
297
     * @static
298
     * @protected
299
     */
300
    _parseMeta: function(metaFields, xmldoc_in, data_out) {
301
        if(Lang.isObject(metaFields)) {
302
            var key,
303
                xmldoc = xmldoc_in.ownerDocument || xmldoc_in;
304
 
305
            for(key in metaFields) {
306
                if (metaFields.hasOwnProperty(key)) {
307
                    data_out.meta[key] = SchemaXML._getLocationValue(metaFields[key], xmldoc);
308
                }
309
            }
310
        }
311
        return data_out;
312
    },
313
 
314
    /**
315
     * Schema-parsed result to add to results list.
316
     *
317
     * @method _parseResult
318
     * @param fields {Array} Required. A collection of field definition.
319
     * @param context {Object} Required. XML node or document to search within.
320
     * @return {Object} Schema-parsed data.
321
     * @static
322
     * @protected
323
     */
324
    _parseResult: function(fields, context) {
325
        var result = {}, j;
326
 
327
        // Find each field value
328
        for (j=fields.length-1; 0 <= j; j--) {
329
            SchemaXML._parseField(fields[j], result, context);
330
        }
331
 
332
        return result;
333
    },
334
 
335
    /**
336
     * Schema-parsed list of results from full data
337
     *
338
     * @method _parseResults
339
     * @param schema {Object} Schema to parse against.
340
     * @param context {Object} XML node or document to parse.
341
     * @param data_out {Object} In-progress schema-parsed data to update.
342
     * @return {Object} Schema-parsed data.
343
     * @static
344
     * @protected
345
     */
346
    _parseResults: function(schema, context, data_out) {
347
        if (schema.resultListLocator && Lang.isArray(schema.resultFields)) {
348
            var xmldoc = context.ownerDocument || context,
349
                fields = schema.resultFields,
350
                results = [],
351
                node, nodeList, i=0;
352
 
353
            if (schema.resultListLocator.match(/^[:\-\w]+$/)) {
354
                nodeList = context.getElementsByTagName(schema.resultListLocator);
355
 
356
                // loop through each result node
357
                for (i = nodeList.length - 1; i >= 0; --i) {
358
                    results[i] = SchemaXML._parseResult(fields, nodeList[i]);
359
                }
360
            } else {
361
                nodeList = SchemaXML._getXPathResult(schema.resultListLocator, context, xmldoc);
362
 
363
                // loop through the nodelist
364
                while ((node = nodeList.iterateNext())) {
365
                    results[i] = SchemaXML._parseResult(fields, node);
366
                    i += 1;
367
                }
368
            }
369
 
370
            if (results.length) {
371
                data_out.results = results;
372
            } else {
373
                data_out.error = new Error("XML schema result nodes retrieval failure");
374
            }
375
        }
376
        return data_out;
377
    }
378
};
379
 
380
Y.DataSchema.XML = Y.mix(SchemaXML, Y.DataSchema.Base);
381
 
382
 
383
}, '3.18.1', {"requires": ["dataschema-base"]});