Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dataschema-xml.js 14KB

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