Version 3.18.1
Show:

File: dataschema/js/dataschema-xml.js

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