xml.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview
  16. * XML utilities.
  17. *
  18. */
  19. goog.provide('goog.dom.xml');
  20. goog.require('goog.dom');
  21. goog.require('goog.dom.NodeType');
  22. goog.require('goog.userAgent');
  23. /**
  24. * Max XML size for MSXML2. Used to prevent potential DoS attacks.
  25. * @type {number}
  26. */
  27. goog.dom.xml.MAX_XML_SIZE_KB = 2 * 1024; // In kB
  28. /**
  29. * Max XML size for MSXML2. Used to prevent potential DoS attacks.
  30. * @type {number}
  31. */
  32. goog.dom.xml.MAX_ELEMENT_DEPTH = 256; // Same default as MSXML6.
  33. /**
  34. * Check for ActiveXObject support by the browser.
  35. * @return {boolean} true if browser has ActiveXObject support.
  36. * @private
  37. */
  38. goog.dom.xml.hasActiveXObjectSupport_ = function() {
  39. if (!goog.userAgent.IE) {
  40. // Avoid raising useless exception in case code is not compiled
  41. // and browser is not MSIE.
  42. return false;
  43. }
  44. try {
  45. // Due to lot of changes in IE 9, 10 & 11 behaviour and ActiveX being
  46. // totally disableable using MSIE's security level, trying to create the
  47. // ActiveXOjbect is a lot more reliable than testing for the existence of
  48. // window.ActiveXObject
  49. new ActiveXObject('MSXML2.DOMDocument');
  50. return true;
  51. } catch (e) {
  52. return false;
  53. }
  54. };
  55. /**
  56. * True if browser has ActiveXObject support.
  57. * Possible override if this test become wrong in coming IE versions.
  58. * @type {boolean}
  59. */
  60. goog.dom.xml.ACTIVEX_SUPPORT =
  61. goog.userAgent.IE && goog.dom.xml.hasActiveXObjectSupport_();
  62. /**
  63. * Creates an XML document appropriate for the current JS runtime
  64. * @param {string=} opt_rootTagName The root tag name.
  65. * @param {string=} opt_namespaceUri Namespace URI of the document element.
  66. * @param {boolean=} opt_preferActiveX Whether to default to ActiveXObject to
  67. * create Document in IE. Use this if you need xpath support in IE (e.g.,
  68. * selectSingleNode or selectNodes), but be aware that the ActiveXObject does
  69. * not support various DOM-specific Document methods and attributes.
  70. * @return {Document} The new document.
  71. * @throws {Error} if browser does not support creating new documents or
  72. * namespace is provided without a root tag name.
  73. */
  74. goog.dom.xml.createDocument = function(
  75. opt_rootTagName, opt_namespaceUri, opt_preferActiveX) {
  76. if (opt_namespaceUri && !opt_rootTagName) {
  77. throw Error("Can't create document with namespace and no root tag");
  78. }
  79. // If document.implementation.createDocument is available and they haven't
  80. // explicitly opted to use ActiveXObject when possible.
  81. if (document.implementation && document.implementation.createDocument &&
  82. !(goog.dom.xml.ACTIVEX_SUPPORT && opt_preferActiveX)) {
  83. return document.implementation.createDocument(
  84. opt_namespaceUri || '', opt_rootTagName || '', null);
  85. } else if (goog.dom.xml.ACTIVEX_SUPPORT) {
  86. var doc = goog.dom.xml.createMsXmlDocument_();
  87. if (doc) {
  88. if (opt_rootTagName) {
  89. doc.appendChild(
  90. doc.createNode(
  91. goog.dom.NodeType.ELEMENT, opt_rootTagName,
  92. opt_namespaceUri || ''));
  93. }
  94. return doc;
  95. }
  96. }
  97. throw Error('Your browser does not support creating new documents');
  98. };
  99. /**
  100. * Creates an XML document from a string
  101. * @param {string} xml The text.
  102. * @param {boolean=} opt_preferActiveX Whether to default to ActiveXObject to
  103. * create Document in IE. Use this if you need xpath support in IE (e.g.,
  104. * selectSingleNode or selectNodes), but be aware that the ActiveXObject does
  105. * not support various DOM-specific Document methods and attributes.
  106. * @return {Document} XML document from the text.
  107. * @throws {Error} if browser does not support loading XML documents.
  108. */
  109. goog.dom.xml.loadXml = function(xml, opt_preferActiveX) {
  110. if (typeof DOMParser != 'undefined' &&
  111. !(goog.dom.xml.ACTIVEX_SUPPORT && opt_preferActiveX)) {
  112. return new DOMParser().parseFromString(xml, 'application/xml');
  113. } else if (goog.dom.xml.ACTIVEX_SUPPORT) {
  114. var doc = goog.dom.xml.createMsXmlDocument_();
  115. doc.loadXML(xml);
  116. return doc;
  117. }
  118. throw Error('Your browser does not support loading xml documents');
  119. };
  120. /**
  121. * Serializes an XML document or subtree to string.
  122. * @param {Document|Element} xml The document or the root node of the subtree.
  123. * @return {string} The serialized XML.
  124. * @throws {Error} if browser does not support XML serialization.
  125. */
  126. goog.dom.xml.serialize = function(xml) {
  127. // Compatible with IE/ActiveXObject.
  128. var text = xml.xml;
  129. if (text) {
  130. return text;
  131. }
  132. // Compatible with Firefox, Opera and WebKit.
  133. if (typeof XMLSerializer != 'undefined') {
  134. return new XMLSerializer().serializeToString(xml);
  135. }
  136. throw Error('Your browser does not support serializing XML documents');
  137. };
  138. /**
  139. * Selects a single node using an Xpath expression and a root node
  140. * @param {Node} node The root node.
  141. * @param {string} path Xpath selector.
  142. * @return {Node} The selected node, or null if no matching node.
  143. */
  144. goog.dom.xml.selectSingleNode = function(node, path) {
  145. if (typeof node.selectSingleNode != 'undefined') {
  146. var doc = goog.dom.getOwnerDocument(node);
  147. if (typeof doc.setProperty != 'undefined') {
  148. doc.setProperty('SelectionLanguage', 'XPath');
  149. }
  150. return node.selectSingleNode(path);
  151. } else if (document.implementation.hasFeature('XPath', '3.0')) {
  152. var doc = goog.dom.getOwnerDocument(node);
  153. var resolver = doc.createNSResolver(doc.documentElement);
  154. var result = doc.evaluate(
  155. path, node, resolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
  156. return result.singleNodeValue;
  157. }
  158. // This browser does not support xpath for the given node. If IE, ensure XML
  159. // Document was created using ActiveXObject
  160. // TODO(joeltine): This should throw instead of return null.
  161. return null;
  162. };
  163. /**
  164. * Selects multiple nodes using an Xpath expression and a root node
  165. * @param {Node} node The root node.
  166. * @param {string} path Xpath selector.
  167. * @return {(!NodeList<!Node>|!Array<!Node>)} The selected nodes, or empty array
  168. * if no matching nodes.
  169. */
  170. goog.dom.xml.selectNodes = function(node, path) {
  171. if (typeof node.selectNodes != 'undefined') {
  172. var doc = goog.dom.getOwnerDocument(node);
  173. if (typeof doc.setProperty != 'undefined') {
  174. doc.setProperty('SelectionLanguage', 'XPath');
  175. }
  176. return node.selectNodes(path);
  177. } else if (document.implementation.hasFeature('XPath', '3.0')) {
  178. var doc = goog.dom.getOwnerDocument(node);
  179. var resolver = doc.createNSResolver(doc.documentElement);
  180. var nodes = doc.evaluate(
  181. path, node, resolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  182. var results = [];
  183. var count = nodes.snapshotLength;
  184. for (var i = 0; i < count; i++) {
  185. results.push(nodes.snapshotItem(i));
  186. }
  187. return results;
  188. } else {
  189. // This browser does not support xpath for the given node. If IE, ensure XML
  190. // Document was created using ActiveXObject.
  191. // TODO(joeltine): This should throw instead of return empty array.
  192. return [];
  193. }
  194. };
  195. /**
  196. * Sets multiple attributes on an element. Differs from goog.dom.setProperties
  197. * in that it exclusively uses the element's setAttributes method. Use this
  198. * when you need to ensure that the exact property is available as an attribute
  199. * and can be read later by the native getAttribute method.
  200. * @param {!Element} element XML or DOM element to set attributes on.
  201. * @param {!Object<string, string>} attributes Map of property:value pairs.
  202. */
  203. goog.dom.xml.setAttributes = function(element, attributes) {
  204. for (var key in attributes) {
  205. if (attributes.hasOwnProperty(key)) {
  206. element.setAttribute(key, attributes[key]);
  207. }
  208. }
  209. };
  210. /**
  211. * Creates an instance of the MSXML2.DOMDocument.
  212. * @return {Document} The new document.
  213. * @private
  214. */
  215. goog.dom.xml.createMsXmlDocument_ = function() {
  216. var doc = new ActiveXObject('MSXML2.DOMDocument');
  217. if (doc) {
  218. // Prevent potential vulnerabilities exposed by MSXML2, see
  219. // http://b/1707300 and http://wiki/Main/ISETeamXMLAttacks for details.
  220. doc.resolveExternals = false;
  221. doc.validateOnParse = false;
  222. // Add a try catch block because accessing these properties will throw an
  223. // error on unsupported MSXML versions. This affects Windows machines
  224. // running IE6 or IE7 that are on XP SP2 or earlier without MSXML updates.
  225. // See http://msdn.microsoft.com/en-us/library/ms766391(VS.85).aspx for
  226. // specific details on which MSXML versions support these properties.
  227. try {
  228. doc.setProperty('ProhibitDTD', true);
  229. doc.setProperty('MaxXMLSize', goog.dom.xml.MAX_XML_SIZE_KB);
  230. doc.setProperty('MaxElementDepth', goog.dom.xml.MAX_ELEMENT_DEPTH);
  231. } catch (e) {
  232. // No-op.
  233. }
  234. }
  235. return doc;
  236. };