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.
 
 
 

1382 lines
50 KiB

  1. # Copyright (c) 2003, The Regents of the University of California,
  2. # through Lawrence Berkeley National Laboratory (subject to receipt of
  3. # any required approvals from the U.S. Dept. of Energy). All rights
  4. # reserved.
  5. #
  6. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
  7. #
  8. # This software is subject to the provisions of the Zope Public License,
  9. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
  10. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  11. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  12. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  13. # FOR A PARTICULAR PURPOSE.
  14. ident = "$Id$"
  15. import sys, types, httplib, urllib, socket, weakref
  16. from os.path import isfile
  17. from string import join, strip, split
  18. from UserDict import UserDict
  19. from cStringIO import StringIO
  20. from TimeoutSocket import TimeoutSocket, TimeoutError
  21. from urlparse import urlparse
  22. from httplib import HTTPConnection, HTTPSConnection
  23. from exceptions import Exception
  24. try:
  25. from ZSI import _get_idstr
  26. except:
  27. def _get_idstr(pyobj):
  28. '''Python 2.3.x generates a FutureWarning for negative IDs, so
  29. we use a different prefix character to ensure uniqueness, and
  30. call abs() to avoid the warning.'''
  31. x = id(pyobj)
  32. if x < 0:
  33. return 'x%x' % abs(x)
  34. return 'o%x' % x
  35. import xml.dom.minidom
  36. from xml.dom import Node
  37. import logging
  38. from c14n import Canonicalize
  39. from Namespaces import SCHEMA, SOAP, XMLNS, ZSI_SCHEMA_URI
  40. try:
  41. from xml.dom.ext import SplitQName
  42. except:
  43. def SplitQName(qname):
  44. '''SplitQName(qname) -> (string, string)
  45. Split Qualified Name into a tuple of len 2, consisting
  46. of the prefix and the local name.
  47. (prefix, localName)
  48. Special Cases:
  49. xmlns -- (localName, 'xmlns')
  50. None -- (None, localName)
  51. '''
  52. l = qname.split(':')
  53. if len(l) == 1:
  54. l.insert(0, None)
  55. elif len(l) == 2:
  56. if l[0] == 'xmlns':
  57. l.reverse()
  58. else:
  59. return
  60. return tuple(l)
  61. #
  62. # python2.3 urllib.basejoin does not remove current directory ./
  63. # from path and this causes problems on subsequent basejoins.
  64. #
  65. basejoin = urllib.basejoin
  66. if sys.version_info[0:2] < (2, 4, 0, 'final', 0)[0:2]:
  67. #basejoin = lambda base,url: urllib.basejoin(base,url.lstrip('./'))
  68. token = './'
  69. def basejoin(base, url):
  70. if url.startswith(token) is True:
  71. return urllib.basejoin(base,url[2:])
  72. return urllib.basejoin(base,url)
  73. class NamespaceError(Exception):
  74. """Used to indicate a Namespace Error."""
  75. class RecursionError(Exception):
  76. """Used to indicate a HTTP redirect recursion."""
  77. class ParseError(Exception):
  78. """Used to indicate a XML parsing error."""
  79. class DOMException(Exception):
  80. """Used to indicate a problem processing DOM."""
  81. class Base:
  82. """Base class for instance level Logging"""
  83. def __init__(self, module=__name__):
  84. self.logger = logging.getLogger('%s-%s(%s)' %(module, self.__class__, _get_idstr(self)))
  85. class HTTPResponse:
  86. """Captures the information in an HTTP response message."""
  87. def __init__(self, response):
  88. self.status = response.status
  89. self.reason = response.reason
  90. self.headers = response.msg
  91. self.body = response.read() or None
  92. response.close()
  93. class TimeoutHTTP(HTTPConnection):
  94. """A custom http connection object that supports socket timeout."""
  95. def __init__(self, host, port=None, timeout=20):
  96. HTTPConnection.__init__(self, host, port)
  97. self.timeout = timeout
  98. def connect(self):
  99. self.sock = TimeoutSocket(self.timeout)
  100. self.sock.connect((self.host, self.port))
  101. class TimeoutHTTPS(HTTPSConnection):
  102. """A custom https object that supports socket timeout. Note that this
  103. is not really complete. The builtin SSL support in the Python socket
  104. module requires a real socket (type) to be passed in to be hooked to
  105. SSL. That means our fake socket won't work and our timeout hacks are
  106. bypassed for send and recv calls. Since our hack _is_ in place at
  107. connect() time, it should at least provide some timeout protection."""
  108. def __init__(self, host, port=None, timeout=20, **kwargs):
  109. HTTPSConnection.__init__(self, str(host), port, **kwargs)
  110. self.timeout = timeout
  111. def connect(self):
  112. sock = TimeoutSocket(self.timeout)
  113. sock.connect((self.host, self.port))
  114. realsock = getattr(sock.sock, '_sock', sock.sock)
  115. ssl = socket.ssl(realsock, self.key_file, self.cert_file)
  116. self.sock = httplib.FakeSocket(sock, ssl)
  117. def urlopen(url, timeout=20, redirects=None):
  118. """A minimal urlopen replacement hack that supports timeouts for http.
  119. Note that this supports GET only."""
  120. scheme, host, path, params, query, frag = urlparse(url)
  121. if not scheme in ('http', 'https'):
  122. return urllib.urlopen(url)
  123. if params: path = '%s;%s' % (path, params)
  124. if query: path = '%s?%s' % (path, query)
  125. if frag: path = '%s#%s' % (path, frag)
  126. if scheme == 'https':
  127. # If ssl is not compiled into Python, you will not get an exception
  128. # until a conn.endheaders() call. We need to know sooner, so use
  129. # getattr.
  130. try:
  131. import M2Crypto
  132. except ImportError:
  133. if not hasattr(socket, 'ssl'):
  134. raise RuntimeError, 'no built-in SSL Support'
  135. conn = TimeoutHTTPS(host, None, timeout)
  136. else:
  137. ctx = M2Crypto.SSL.Context()
  138. ctx.set_session_timeout(timeout)
  139. conn = M2Crypto.httpslib.HTTPSConnection(host, ssl_context=ctx)
  140. conn.set_debuglevel(1)
  141. else:
  142. conn = TimeoutHTTP(host, None, timeout)
  143. conn.putrequest('GET', path)
  144. conn.putheader('Connection', 'close')
  145. conn.endheaders()
  146. response = None
  147. while 1:
  148. response = conn.getresponse()
  149. if response.status != 100:
  150. break
  151. conn._HTTPConnection__state = httplib._CS_REQ_SENT
  152. conn._HTTPConnection__response = None
  153. status = response.status
  154. # If we get an HTTP redirect, we will follow it automatically.
  155. if status >= 300 and status < 400:
  156. location = response.msg.getheader('location')
  157. if location is not None:
  158. response.close()
  159. if redirects is not None and redirects.has_key(location):
  160. raise RecursionError(
  161. 'Circular HTTP redirection detected.'
  162. )
  163. if redirects is None:
  164. redirects = {}
  165. redirects[location] = 1
  166. return urlopen(location, timeout, redirects)
  167. raise HTTPResponse(response)
  168. if not (status >= 200 and status < 300):
  169. raise HTTPResponse(response)
  170. body = StringIO(response.read())
  171. response.close()
  172. return body
  173. class DOM:
  174. """The DOM singleton defines a number of XML related constants and
  175. provides a number of utility methods for DOM related tasks. It
  176. also provides some basic abstractions so that the rest of the
  177. package need not care about actual DOM implementation in use."""
  178. # Namespace stuff related to the SOAP specification.
  179. NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/'
  180. NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/'
  181. NS_SOAP_ENV_1_2 = 'http://www.w3.org/2001/06/soap-envelope'
  182. NS_SOAP_ENC_1_2 = 'http://www.w3.org/2001/06/soap-encoding'
  183. NS_SOAP_ENV_ALL = (NS_SOAP_ENV_1_1, NS_SOAP_ENV_1_2)
  184. NS_SOAP_ENC_ALL = (NS_SOAP_ENC_1_1, NS_SOAP_ENC_1_2)
  185. NS_SOAP_ENV = NS_SOAP_ENV_1_1
  186. NS_SOAP_ENC = NS_SOAP_ENC_1_1
  187. _soap_uri_mapping = {
  188. NS_SOAP_ENV_1_1 : '1.1',
  189. NS_SOAP_ENV_1_2 : '1.2',
  190. }
  191. SOAP_ACTOR_NEXT_1_1 = 'http://schemas.xmlsoap.org/soap/actor/next'
  192. SOAP_ACTOR_NEXT_1_2 = 'http://www.w3.org/2001/06/soap-envelope/actor/next'
  193. SOAP_ACTOR_NEXT_ALL = (SOAP_ACTOR_NEXT_1_1, SOAP_ACTOR_NEXT_1_2)
  194. def SOAPUriToVersion(self, uri):
  195. """Return the SOAP version related to an envelope uri."""
  196. value = self._soap_uri_mapping.get(uri)
  197. if value is not None:
  198. return value
  199. raise ValueError(
  200. 'Unsupported SOAP envelope uri: %s' % uri
  201. )
  202. def GetSOAPEnvUri(self, version):
  203. """Return the appropriate SOAP envelope uri for a given
  204. human-friendly SOAP version string (e.g. '1.1')."""
  205. attrname = 'NS_SOAP_ENV_%s' % join(split(version, '.'), '_')
  206. value = getattr(self, attrname, None)
  207. if value is not None:
  208. return value
  209. raise ValueError(
  210. 'Unsupported SOAP version: %s' % version
  211. )
  212. def GetSOAPEncUri(self, version):
  213. """Return the appropriate SOAP encoding uri for a given
  214. human-friendly SOAP version string (e.g. '1.1')."""
  215. attrname = 'NS_SOAP_ENC_%s' % join(split(version, '.'), '_')
  216. value = getattr(self, attrname, None)
  217. if value is not None:
  218. return value
  219. raise ValueError(
  220. 'Unsupported SOAP version: %s' % version
  221. )
  222. def GetSOAPActorNextUri(self, version):
  223. """Return the right special next-actor uri for a given
  224. human-friendly SOAP version string (e.g. '1.1')."""
  225. attrname = 'SOAP_ACTOR_NEXT_%s' % join(split(version, '.'), '_')
  226. value = getattr(self, attrname, None)
  227. if value is not None:
  228. return value
  229. raise ValueError(
  230. 'Unsupported SOAP version: %s' % version
  231. )
  232. # Namespace stuff related to XML Schema.
  233. NS_XSD_99 = 'http://www.w3.org/1999/XMLSchema'
  234. NS_XSI_99 = 'http://www.w3.org/1999/XMLSchema-instance'
  235. NS_XSD_00 = 'http://www.w3.org/2000/10/XMLSchema'
  236. NS_XSI_00 = 'http://www.w3.org/2000/10/XMLSchema-instance'
  237. NS_XSD_01 = 'http://www.w3.org/2001/XMLSchema'
  238. NS_XSI_01 = 'http://www.w3.org/2001/XMLSchema-instance'
  239. NS_XSD_ALL = (NS_XSD_99, NS_XSD_00, NS_XSD_01)
  240. NS_XSI_ALL = (NS_XSI_99, NS_XSI_00, NS_XSI_01)
  241. NS_XSD = NS_XSD_01
  242. NS_XSI = NS_XSI_01
  243. _xsd_uri_mapping = {
  244. NS_XSD_99 : NS_XSI_99,
  245. NS_XSD_00 : NS_XSI_00,
  246. NS_XSD_01 : NS_XSI_01,
  247. }
  248. for key, value in _xsd_uri_mapping.items():
  249. _xsd_uri_mapping[value] = key
  250. def InstanceUriForSchemaUri(self, uri):
  251. """Return the appropriate matching XML Schema instance uri for
  252. the given XML Schema namespace uri."""
  253. return self._xsd_uri_mapping.get(uri)
  254. def SchemaUriForInstanceUri(self, uri):
  255. """Return the appropriate matching XML Schema namespace uri for
  256. the given XML Schema instance namespace uri."""
  257. return self._xsd_uri_mapping.get(uri)
  258. # Namespace stuff related to WSDL.
  259. NS_WSDL_1_1 = 'http://schemas.xmlsoap.org/wsdl/'
  260. NS_WSDL_ALL = (NS_WSDL_1_1,)
  261. NS_WSDL = NS_WSDL_1_1
  262. NS_SOAP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/soap/'
  263. NS_HTTP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/http/'
  264. NS_MIME_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/mime/'
  265. NS_SOAP_BINDING_ALL = (NS_SOAP_BINDING_1_1,)
  266. NS_HTTP_BINDING_ALL = (NS_HTTP_BINDING_1_1,)
  267. NS_MIME_BINDING_ALL = (NS_MIME_BINDING_1_1,)
  268. NS_SOAP_BINDING = NS_SOAP_BINDING_1_1
  269. NS_HTTP_BINDING = NS_HTTP_BINDING_1_1
  270. NS_MIME_BINDING = NS_MIME_BINDING_1_1
  271. NS_SOAP_HTTP_1_1 = 'http://schemas.xmlsoap.org/soap/http'
  272. NS_SOAP_HTTP_ALL = (NS_SOAP_HTTP_1_1,)
  273. NS_SOAP_HTTP = NS_SOAP_HTTP_1_1
  274. _wsdl_uri_mapping = {
  275. NS_WSDL_1_1 : '1.1',
  276. }
  277. def WSDLUriToVersion(self, uri):
  278. """Return the WSDL version related to a WSDL namespace uri."""
  279. value = self._wsdl_uri_mapping.get(uri)
  280. if value is not None:
  281. return value
  282. raise ValueError(
  283. 'Unsupported SOAP envelope uri: %s' % uri
  284. )
  285. def GetWSDLUri(self, version):
  286. attr = 'NS_WSDL_%s' % join(split(version, '.'), '_')
  287. value = getattr(self, attr, None)
  288. if value is not None:
  289. return value
  290. raise ValueError(
  291. 'Unsupported WSDL version: %s' % version
  292. )
  293. def GetWSDLSoapBindingUri(self, version):
  294. attr = 'NS_SOAP_BINDING_%s' % join(split(version, '.'), '_')
  295. value = getattr(self, attr, None)
  296. if value is not None:
  297. return value
  298. raise ValueError(
  299. 'Unsupported WSDL version: %s' % version
  300. )
  301. def GetWSDLHttpBindingUri(self, version):
  302. attr = 'NS_HTTP_BINDING_%s' % join(split(version, '.'), '_')
  303. value = getattr(self, attr, None)
  304. if value is not None:
  305. return value
  306. raise ValueError(
  307. 'Unsupported WSDL version: %s' % version
  308. )
  309. def GetWSDLMimeBindingUri(self, version):
  310. attr = 'NS_MIME_BINDING_%s' % join(split(version, '.'), '_')
  311. value = getattr(self, attr, None)
  312. if value is not None:
  313. return value
  314. raise ValueError(
  315. 'Unsupported WSDL version: %s' % version
  316. )
  317. def GetWSDLHttpTransportUri(self, version):
  318. attr = 'NS_SOAP_HTTP_%s' % join(split(version, '.'), '_')
  319. value = getattr(self, attr, None)
  320. if value is not None:
  321. return value
  322. raise ValueError(
  323. 'Unsupported WSDL version: %s' % version
  324. )
  325. # Other xml namespace constants.
  326. NS_XMLNS = 'http://www.w3.org/2000/xmlns/'
  327. def isElement(self, node, name, nsuri=None):
  328. """Return true if the given node is an element with the given
  329. name and optional namespace uri."""
  330. if node.nodeType != node.ELEMENT_NODE:
  331. return 0
  332. return node.localName == name and \
  333. (nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))
  334. def getElement(self, node, name, nsuri=None, default=join):
  335. """Return the first child of node with a matching name and
  336. namespace uri, or the default if one is provided."""
  337. nsmatch = self.nsUriMatch
  338. ELEMENT_NODE = node.ELEMENT_NODE
  339. for child in node.childNodes:
  340. if child.nodeType == ELEMENT_NODE:
  341. if ((child.localName == name or name is None) and
  342. (nsuri is None or nsmatch(child.namespaceURI, nsuri))
  343. ):
  344. return child
  345. if default is not join:
  346. return default
  347. raise KeyError, name
  348. def getElementById(self, node, id, default=join):
  349. """Return the first child of node matching an id reference."""
  350. attrget = self.getAttr
  351. ELEMENT_NODE = node.ELEMENT_NODE
  352. for child in node.childNodes:
  353. if child.nodeType == ELEMENT_NODE:
  354. if attrget(child, 'id') == id:
  355. return child
  356. if default is not join:
  357. return default
  358. raise KeyError, name
  359. def getMappingById(self, document, depth=None, element=None,
  360. mapping=None, level=1):
  361. """Create an id -> element mapping of those elements within a
  362. document that define an id attribute. The depth of the search
  363. may be controlled by using the (1-based) depth argument."""
  364. if document is not None:
  365. element = document.documentElement
  366. mapping = {}
  367. attr = element._attrs.get('id', None)
  368. if attr is not None:
  369. mapping[attr.value] = element
  370. if depth is None or depth > level:
  371. level = level + 1
  372. ELEMENT_NODE = element.ELEMENT_NODE
  373. for child in element.childNodes:
  374. if child.nodeType == ELEMENT_NODE:
  375. self.getMappingById(None, depth, child, mapping, level)
  376. return mapping
  377. def getElements(self, node, name, nsuri=None):
  378. """Return a sequence of the child elements of the given node that
  379. match the given name and optional namespace uri."""
  380. nsmatch = self.nsUriMatch
  381. result = []
  382. ELEMENT_NODE = node.ELEMENT_NODE
  383. for child in node.childNodes:
  384. if child.nodeType == ELEMENT_NODE:
  385. if ((child.localName == name or name is None) and (
  386. (nsuri is None) or nsmatch(child.namespaceURI, nsuri))):
  387. result.append(child)
  388. return result
  389. def hasAttr(self, node, name, nsuri=None):
  390. """Return true if element has attribute with the given name and
  391. optional nsuri. If nsuri is not specified, returns true if an
  392. attribute exists with the given name with any namespace."""
  393. if nsuri is None:
  394. if node.hasAttribute(name):
  395. return True
  396. return False
  397. return node.hasAttributeNS(nsuri, name)
  398. def getAttr(self, node, name, nsuri=None, default=join):
  399. """Return the value of the attribute named 'name' with the
  400. optional nsuri, or the default if one is specified. If
  401. nsuri is not specified, an attribute that matches the
  402. given name will be returned regardless of namespace."""
  403. if nsuri is None:
  404. result = node._attrs.get(name, None)
  405. if result is None:
  406. for item in node._attrsNS.keys():
  407. if item[1] == name:
  408. result = node._attrsNS[item]
  409. break
  410. else:
  411. result = node._attrsNS.get((nsuri, name), None)
  412. if result is not None:
  413. return result.value
  414. if default is not join:
  415. return default
  416. return ''
  417. def getAttrs(self, node):
  418. """Return a Collection of all attributes
  419. """
  420. attrs = {}
  421. for k,v in node._attrs.items():
  422. attrs[k] = v.value
  423. return attrs
  424. def getElementText(self, node, preserve_ws=None):
  425. """Return the text value of an xml element node. Leading and trailing
  426. whitespace is stripped from the value unless the preserve_ws flag
  427. is passed with a true value."""
  428. result = []
  429. for child in node.childNodes:
  430. nodetype = child.nodeType
  431. if nodetype == child.TEXT_NODE or \
  432. nodetype == child.CDATA_SECTION_NODE:
  433. result.append(child.nodeValue)
  434. value = join(result, '')
  435. if preserve_ws is None:
  436. value = strip(value)
  437. return value
  438. def findNamespaceURI(self, prefix, node):
  439. """Find a namespace uri given a prefix and a context node."""
  440. attrkey = (self.NS_XMLNS, prefix)
  441. DOCUMENT_NODE = node.DOCUMENT_NODE
  442. ELEMENT_NODE = node.ELEMENT_NODE
  443. while 1:
  444. if node is None:
  445. raise DOMException('Value for prefix %s not found.' % prefix)
  446. if node.nodeType != ELEMENT_NODE:
  447. node = node.parentNode
  448. continue
  449. result = node._attrsNS.get(attrkey, None)
  450. if result is not None:
  451. return result.value
  452. if hasattr(node, '__imported__'):
  453. raise DOMException('Value for prefix %s not found.' % prefix)
  454. node = node.parentNode
  455. if node.nodeType == DOCUMENT_NODE:
  456. raise DOMException('Value for prefix %s not found.' % prefix)
  457. def findDefaultNS(self, node):
  458. """Return the current default namespace uri for the given node."""
  459. attrkey = (self.NS_XMLNS, 'xmlns')
  460. DOCUMENT_NODE = node.DOCUMENT_NODE
  461. ELEMENT_NODE = node.ELEMENT_NODE
  462. while 1:
  463. if node.nodeType != ELEMENT_NODE:
  464. node = node.parentNode
  465. continue
  466. result = node._attrsNS.get(attrkey, None)
  467. if result is not None:
  468. return result.value
  469. if hasattr(node, '__imported__'):
  470. raise DOMException('Cannot determine default namespace.')
  471. node = node.parentNode
  472. if node.nodeType == DOCUMENT_NODE:
  473. raise DOMException('Cannot determine default namespace.')
  474. def findTargetNS(self, node):
  475. """Return the defined target namespace uri for the given node."""
  476. attrget = self.getAttr
  477. attrkey = (self.NS_XMLNS, 'xmlns')
  478. DOCUMENT_NODE = node.DOCUMENT_NODE
  479. ELEMENT_NODE = node.ELEMENT_NODE
  480. while 1:
  481. if node.nodeType != ELEMENT_NODE:
  482. node = node.parentNode
  483. continue
  484. result = attrget(node, 'targetNamespace', default=None)
  485. if result is not None:
  486. return result
  487. node = node.parentNode
  488. if node.nodeType == DOCUMENT_NODE:
  489. raise DOMException('Cannot determine target namespace.')
  490. def getTypeRef(self, element):
  491. """Return (namespaceURI, name) for a type attribue of the given
  492. element, or None if the element does not have a type attribute."""
  493. typeattr = self.getAttr(element, 'type', default=None)
  494. if typeattr is None:
  495. return None
  496. parts = typeattr.split(':', 1)
  497. if len(parts) == 2:
  498. nsuri = self.findNamespaceURI(parts[0], element)
  499. else:
  500. nsuri = self.findDefaultNS(element)
  501. return (nsuri, parts[1])
  502. def importNode(self, document, node, deep=0):
  503. """Implements (well enough for our purposes) DOM node import."""
  504. nodetype = node.nodeType
  505. if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
  506. raise DOMException('Illegal node type for importNode')
  507. if nodetype == node.ENTITY_REFERENCE_NODE:
  508. deep = 0
  509. clone = node.cloneNode(deep)
  510. self._setOwnerDoc(document, clone)
  511. clone.__imported__ = 1
  512. return clone
  513. def _setOwnerDoc(self, document, node):
  514. node.ownerDocument = document
  515. for child in node.childNodes:
  516. self._setOwnerDoc(document, child)
  517. def nsUriMatch(self, value, wanted, strict=0, tt=type(())):
  518. """Return a true value if two namespace uri values match."""
  519. if value == wanted or (type(wanted) is tt) and value in wanted:
  520. return 1
  521. if not strict and value is not None:
  522. wanted = type(wanted) is tt and wanted or (wanted,)
  523. value = value[-1:] != '/' and value or value[:-1]
  524. for item in wanted:
  525. if item == value or item[:-1] == value:
  526. return 1
  527. return 0
  528. def createDocument(self, nsuri, qname, doctype=None):
  529. """Create a new writable DOM document object."""
  530. impl = xml.dom.minidom.getDOMImplementation()
  531. return impl.createDocument(nsuri, qname, doctype)
  532. def loadDocument(self, data):
  533. """Load an xml file from a file-like object and return a DOM
  534. document instance."""
  535. return xml.dom.minidom.parse(data)
  536. def loadFromURL(self, url):
  537. """Load an xml file from a URL and return a DOM document."""
  538. if isfile(url) is True:
  539. file = open(url, 'r')
  540. else:
  541. file = urlopen(url)
  542. try:
  543. result = self.loadDocument(file)
  544. except Exception, ex:
  545. file.close()
  546. raise ParseError(('Failed to load document %s' %url,) + ex.args)
  547. else:
  548. file.close()
  549. return result
  550. DOM = DOM()
  551. class MessageInterface:
  552. '''Higher Level Interface, delegates to DOM singleton, must
  553. be subclassed and implement all methods that throw NotImplementedError.
  554. '''
  555. def __init__(self, sw):
  556. '''Constructor, May be extended, do not override.
  557. sw -- soapWriter instance
  558. '''
  559. self.sw = None
  560. if type(sw) != weakref.ReferenceType and sw is not None:
  561. self.sw = weakref.ref(sw)
  562. else:
  563. self.sw = sw
  564. def AddCallback(self, func, *arglist):
  565. self.sw().AddCallback(func, *arglist)
  566. def Known(self, obj):
  567. return self.sw().Known(obj)
  568. def Forget(self, obj):
  569. return self.sw().Forget(obj)
  570. def canonicalize(self):
  571. '''canonicalize the underlying DOM, and return as string.
  572. '''
  573. raise NotImplementedError, ''
  574. def createDocument(self, namespaceURI=SOAP.ENV, localName='Envelope'):
  575. '''create Document
  576. '''
  577. raise NotImplementedError, ''
  578. def createAppendElement(self, namespaceURI, localName):
  579. '''create and append element(namespaceURI,localName), and return
  580. the node.
  581. '''
  582. raise NotImplementedError, ''
  583. def findNamespaceURI(self, qualifiedName):
  584. raise NotImplementedError, ''
  585. def resolvePrefix(self, prefix):
  586. raise NotImplementedError, ''
  587. def setAttributeNS(self, namespaceURI, localName, value):
  588. '''set attribute (namespaceURI, localName)=value
  589. '''
  590. raise NotImplementedError, ''
  591. def setAttributeType(self, namespaceURI, localName):
  592. '''set attribute xsi:type=(namespaceURI, localName)
  593. '''
  594. raise NotImplementedError, ''
  595. def setNamespaceAttribute(self, namespaceURI, prefix):
  596. '''set namespace attribute xmlns:prefix=namespaceURI
  597. '''
  598. raise NotImplementedError, ''
  599. class ElementProxy(Base, MessageInterface):
  600. '''
  601. '''
  602. _soap_env_prefix = 'SOAP-ENV'
  603. _soap_enc_prefix = 'SOAP-ENC'
  604. _zsi_prefix = 'ZSI'
  605. _xsd_prefix = 'xsd'
  606. _xsi_prefix = 'xsi'
  607. _xml_prefix = 'xml'
  608. _xmlns_prefix = 'xmlns'
  609. _soap_env_nsuri = SOAP.ENV
  610. _soap_enc_nsuri = SOAP.ENC
  611. _zsi_nsuri = ZSI_SCHEMA_URI
  612. _xsd_nsuri = SCHEMA.XSD3
  613. _xsi_nsuri = SCHEMA.XSI3
  614. _xml_nsuri = XMLNS.XML
  615. _xmlns_nsuri = XMLNS.BASE
  616. standard_ns = {\
  617. _xml_prefix:_xml_nsuri,
  618. _xmlns_prefix:_xmlns_nsuri
  619. }
  620. reserved_ns = {\
  621. _soap_env_prefix:_soap_env_nsuri,
  622. _soap_enc_prefix:_soap_enc_nsuri,
  623. _zsi_prefix:_zsi_nsuri,
  624. _xsd_prefix:_xsd_nsuri,
  625. _xsi_prefix:_xsi_nsuri,
  626. }
  627. name = None
  628. namespaceURI = None
  629. def __init__(self, sw, message=None):
  630. '''Initialize.
  631. sw -- SoapWriter
  632. '''
  633. self._indx = 0
  634. MessageInterface.__init__(self, sw)
  635. Base.__init__(self)
  636. self._dom = DOM
  637. self.node = None
  638. if type(message) in (types.StringType,types.UnicodeType):
  639. self.loadFromString(message)
  640. elif isinstance(message, ElementProxy):
  641. self.node = message._getNode()
  642. else:
  643. self.node = message
  644. self.processorNss = self.standard_ns.copy()
  645. self.processorNss.update(self.reserved_ns)
  646. def __str__(self):
  647. return self.toString()
  648. def evaluate(self, expression, processorNss=None):
  649. '''expression -- XPath compiled expression
  650. '''
  651. from Ft.Xml import XPath
  652. if not processorNss:
  653. context = XPath.Context.Context(self.node, processorNss=self.processorNss)
  654. else:
  655. context = XPath.Context.Context(self.node, processorNss=processorNss)
  656. nodes = expression.evaluate(context)
  657. return map(lambda node: ElementProxy(self.sw,node), nodes)
  658. #############################################
  659. # Methods for checking/setting the
  660. # classes (namespaceURI,name) node.
  661. #############################################
  662. def checkNode(self, namespaceURI=None, localName=None):
  663. '''
  664. namespaceURI -- namespace of element
  665. localName -- local name of element
  666. '''
  667. namespaceURI = namespaceURI or self.namespaceURI
  668. localName = localName or self.name
  669. check = False
  670. if localName and self.node:
  671. check = self._dom.isElement(self.node, localName, namespaceURI)
  672. if not check:
  673. raise NamespaceError, 'unexpected node type %s, expecting %s' %(self.node, localName)
  674. def setNode(self, node=None):
  675. if node:
  676. if isinstance(node, ElementProxy):
  677. self.node = node._getNode()
  678. else:
  679. self.node = node
  680. elif self.node:
  681. node = self._dom.getElement(self.node, self.name, self.namespaceURI, default=None)
  682. if not node:
  683. raise NamespaceError, 'cant find element (%s,%s)' %(self.namespaceURI,self.name)
  684. self.node = node
  685. else:
  686. #self.node = self._dom.create(self.node, self.name, self.namespaceURI, default=None)
  687. self.createDocument(self.namespaceURI, localName=self.name, doctype=None)
  688. self.checkNode()
  689. #############################################
  690. # Wrapper Methods for direct DOM Element Node access
  691. #############################################
  692. def _getNode(self):
  693. return self.node
  694. def _getElements(self):
  695. return self._dom.getElements(self.node, name=None)
  696. def _getOwnerDocument(self):
  697. return self.node.ownerDocument or self.node
  698. def _getUniquePrefix(self):
  699. '''I guess we need to resolve all potential prefixes
  700. because when the current node is attached it copies the
  701. namespaces into the parent node.
  702. '''
  703. while 1:
  704. self._indx += 1
  705. prefix = 'ns%d' %self._indx
  706. try:
  707. self._dom.findNamespaceURI(prefix, self._getNode())
  708. except DOMException, ex:
  709. break
  710. return prefix
  711. def _getPrefix(self, node, nsuri):
  712. '''
  713. Keyword arguments:
  714. node -- DOM Element Node
  715. nsuri -- namespace of attribute value
  716. '''
  717. try:
  718. if node and (node.nodeType == node.ELEMENT_NODE) and \
  719. (nsuri == self._dom.findDefaultNS(node)):
  720. return None
  721. except DOMException, ex:
  722. pass
  723. if nsuri == XMLNS.XML:
  724. return self._xml_prefix
  725. if node.nodeType == Node.ELEMENT_NODE:
  726. for attr in node.attributes.values():
  727. if attr.namespaceURI == XMLNS.BASE \
  728. and nsuri == attr.value:
  729. return attr.localName
  730. else:
  731. if node.parentNode:
  732. return self._getPrefix(node.parentNode, nsuri)
  733. raise NamespaceError, 'namespaceURI "%s" is not defined' %nsuri
  734. def _appendChild(self, node):
  735. '''
  736. Keyword arguments:
  737. node -- DOM Element Node
  738. '''
  739. if node is None:
  740. raise TypeError, 'node is None'
  741. self.node.appendChild(node)
  742. def _insertBefore(self, newChild, refChild):
  743. '''
  744. Keyword arguments:
  745. child -- DOM Element Node to insert
  746. refChild -- DOM Element Node
  747. '''
  748. self.node.insertBefore(newChild, refChild)
  749. def _setAttributeNS(self, namespaceURI, qualifiedName, value):
  750. '''
  751. Keyword arguments:
  752. namespaceURI -- namespace of attribute
  753. qualifiedName -- qualified name of new attribute value
  754. value -- value of attribute
  755. '''
  756. self.node.setAttributeNS(namespaceURI, qualifiedName, value)
  757. #############################################
  758. #General Methods
  759. #############################################
  760. def isFault(self):
  761. '''check to see if this is a soap:fault message.
  762. '''
  763. return False
  764. def getPrefix(self, namespaceURI):
  765. try:
  766. prefix = self._getPrefix(node=self.node, nsuri=namespaceURI)
  767. except NamespaceError, ex:
  768. prefix = self._getUniquePrefix()
  769. self.setNamespaceAttribute(prefix, namespaceURI)
  770. return prefix
  771. def getDocument(self):
  772. return self._getOwnerDocument()
  773. def setDocument(self, document):
  774. self.node = document
  775. def importFromString(self, xmlString):
  776. doc = self._dom.loadDocument(StringIO(xmlString))
  777. node = self._dom.getElement(doc, name=None)
  778. clone = self.importNode(node)
  779. self._appendChild(clone)
  780. def importNode(self, node):
  781. if isinstance(node, ElementProxy):
  782. node = node._getNode()
  783. return self._dom.importNode(self._getOwnerDocument(), node, deep=1)
  784. def loadFromString(self, data):
  785. self.node = self._dom.loadDocument(StringIO(data))
  786. def canonicalize(self):
  787. return Canonicalize(self.node)
  788. def toString(self):
  789. return self.canonicalize()
  790. def createDocument(self, namespaceURI, localName, doctype=None):
  791. '''If specified must be a SOAP envelope, else may contruct an empty document.
  792. '''
  793. prefix = self._soap_env_prefix
  794. if namespaceURI == self.reserved_ns[prefix]:
  795. qualifiedName = '%s:%s' %(prefix,localName)
  796. elif namespaceURI is localName is None:
  797. self.node = self._dom.createDocument(None,None,None)
  798. return
  799. else:
  800. raise KeyError, 'only support creation of document in %s' %self.reserved_ns[prefix]
  801. document = self._dom.createDocument(nsuri=namespaceURI, qname=qualifiedName, doctype=doctype)
  802. self.node = document.childNodes[0]
  803. #set up reserved namespace attributes
  804. for prefix,nsuri in self.reserved_ns.items():
  805. self._setAttributeNS(namespaceURI=self._xmlns_nsuri,
  806. qualifiedName='%s:%s' %(self._xmlns_prefix,prefix),
  807. value=nsuri)
  808. #############################################
  809. #Methods for attributes
  810. #############################################
  811. def hasAttribute(self, namespaceURI, localName):
  812. return self._dom.hasAttr(self._getNode(), name=localName, nsuri=namespaceURI)
  813. def setAttributeType(self, namespaceURI, localName):
  814. '''set xsi:type
  815. Keyword arguments:
  816. namespaceURI -- namespace of attribute value
  817. localName -- name of new attribute value
  818. '''
  819. self.logger.debug('setAttributeType: (%s,%s)', namespaceURI, localName)
  820. value = localName
  821. if namespaceURI:
  822. value = '%s:%s' %(self.getPrefix(namespaceURI),localName)
  823. xsi_prefix = self.getPrefix(self._xsi_nsuri)
  824. self._setAttributeNS(self._xsi_nsuri, '%s:type' %xsi_prefix, value)
  825. def createAttributeNS(self, namespace, name, value):
  826. document = self._getOwnerDocument()
  827. attrNode = document.createAttributeNS(namespace, name, value)
  828. def setAttributeNS(self, namespaceURI, localName, value):
  829. '''
  830. Keyword arguments:
  831. namespaceURI -- namespace of attribute to create, None is for
  832. attributes in no namespace.
  833. localName -- local name of new attribute
  834. value -- value of new attribute
  835. '''
  836. prefix = None
  837. if namespaceURI:
  838. try:
  839. prefix = self.getPrefix(namespaceURI)
  840. except KeyError, ex:
  841. prefix = 'ns2'
  842. self.setNamespaceAttribute(prefix, namespaceURI)
  843. qualifiedName = localName
  844. if prefix:
  845. qualifiedName = '%s:%s' %(prefix, localName)
  846. self._setAttributeNS(namespaceURI, qualifiedName, value)
  847. def setNamespaceAttribute(self, prefix, namespaceURI):
  848. '''
  849. Keyword arguments:
  850. prefix -- xmlns prefix
  851. namespaceURI -- value of prefix
  852. '''
  853. self._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
  854. #############################################
  855. #Methods for elements
  856. #############################################
  857. def createElementNS(self, namespace, qname):
  858. '''
  859. Keyword arguments:
  860. namespace -- namespace of element to create
  861. qname -- qualified name of new element
  862. '''
  863. document = self._getOwnerDocument()
  864. node = document.createElementNS(namespace, qname)
  865. return ElementProxy(self.sw, node)
  866. def createAppendSetElement(self, namespaceURI, localName, prefix=None):
  867. '''Create a new element (namespaceURI,name), append it
  868. to current node, then set it to be the current node.
  869. Keyword arguments:
  870. namespaceURI -- namespace of element to create
  871. localName -- local name of new element
  872. prefix -- if namespaceURI is not defined, declare prefix. defaults
  873. to 'ns1' if left unspecified.
  874. '''
  875. node = self.createAppendElement(namespaceURI, localName, prefix=None)
  876. node=node._getNode()
  877. self._setNode(node._getNode())
  878. def createAppendElement(self, namespaceURI, localName, prefix=None):
  879. '''Create a new element (namespaceURI,name), append it
  880. to current node, and return the newly created node.
  881. Keyword arguments:
  882. namespaceURI -- namespace of element to create
  883. localName -- local name of new element
  884. prefix -- if namespaceURI is not defined, declare prefix. defaults
  885. to 'ns1' if left unspecified.
  886. '''
  887. declare = False
  888. qualifiedName = localName
  889. if namespaceURI:
  890. try:
  891. prefix = self.getPrefix(namespaceURI)
  892. except:
  893. declare = True
  894. prefix = prefix or self._getUniquePrefix()
  895. if prefix:
  896. qualifiedName = '%s:%s' %(prefix, localName)
  897. node = self.createElementNS(namespaceURI, qualifiedName)
  898. if declare:
  899. node._setAttributeNS(XMLNS.BASE, 'xmlns:%s' %prefix, namespaceURI)
  900. self._appendChild(node=node._getNode())
  901. return node
  902. def createInsertBefore(self, namespaceURI, localName, refChild):
  903. qualifiedName = localName
  904. prefix = self.getPrefix(namespaceURI)
  905. if prefix:
  906. qualifiedName = '%s:%s' %(prefix, localName)
  907. node = self.createElementNS(namespaceURI, qualifiedName)
  908. self._insertBefore(newChild=node._getNode(), refChild=refChild._getNode())
  909. return node
  910. def getElement(self, namespaceURI, localName):
  911. '''
  912. Keyword arguments:
  913. namespaceURI -- namespace of element
  914. localName -- local name of element
  915. '''
  916. node = self._dom.getElement(self.node, localName, namespaceURI, default=None)
  917. if node:
  918. return ElementProxy(self.sw, node)
  919. return None
  920. def getAttributeValue(self, namespaceURI, localName):
  921. '''
  922. Keyword arguments:
  923. namespaceURI -- namespace of attribute
  924. localName -- local name of attribute
  925. '''
  926. if self.hasAttribute(namespaceURI, localName):
  927. attr = self.node.getAttributeNodeNS(namespaceURI,localName)
  928. return attr.value
  929. return None
  930. def getValue(self):
  931. return self._dom.getElementText(self.node, preserve_ws=True)
  932. #############################################
  933. #Methods for text nodes
  934. #############################################
  935. def createAppendTextNode(self, pyobj):
  936. node = self.createTextNode(pyobj)
  937. self._appendChild(node=node._getNode())
  938. return node
  939. def createTextNode(self, pyobj):
  940. document = self._getOwnerDocument()
  941. node = document.createTextNode(pyobj)
  942. return ElementProxy(self.sw, node)
  943. #############################################
  944. #Methods for retrieving namespaceURI's
  945. #############################################
  946. def findNamespaceURI(self, qualifiedName):
  947. parts = SplitQName(qualifiedName)
  948. element = self._getNode()
  949. if len(parts) == 1:
  950. return (self._dom.findTargetNS(element), value)
  951. return self._dom.findNamespaceURI(parts[0], element)
  952. def resolvePrefix(self, prefix):
  953. element = self._getNode()
  954. return self._dom.findNamespaceURI(prefix, element)
  955. def getSOAPEnvURI(self):
  956. return self._soap_env_nsuri
  957. def isEmpty(self):
  958. return not self.node
  959. class Collection(UserDict):
  960. """Helper class for maintaining ordered named collections."""
  961. default = lambda self,k: k.name
  962. def __init__(self, parent, key=None):
  963. UserDict.__init__(self)
  964. self.parent = weakref.ref(parent)
  965. self.list = []
  966. self._func = key or self.default
  967. def __getitem__(self, key):
  968. if type(key) is type(1):
  969. return self.list[key]
  970. return self.data[key]
  971. def __setitem__(self, key, item):
  972. item.parent = weakref.ref(self)
  973. self.list.append(item)
  974. self.data[key] = item
  975. def keys(self):
  976. return map(lambda i: self._func(i), self.list)
  977. def items(self):
  978. return map(lambda i: (self._func(i), i), self.list)
  979. def values(self):
  980. return self.list
  981. class CollectionNS(UserDict):
  982. """Helper class for maintaining ordered named collections."""
  983. default = lambda self,k: k.name
  984. def __init__(self, parent, key=None):
  985. UserDict.__init__(self)
  986. self.parent = weakref.ref(parent)
  987. self.targetNamespace = None
  988. self.list = []
  989. self._func = key or self.default
  990. def __getitem__(self, key):
  991. self.targetNamespace = self.parent().targetNamespace
  992. if type(key) is types.IntType:
  993. return self.list[key]
  994. elif self.__isSequence(key):
  995. nsuri,name = key
  996. return self.data[nsuri][name]
  997. return self.data[self.parent().targetNamespace][key]
  998. def __setitem__(self, key, item):
  999. item.parent = weakref.ref(self)
  1000. self.list.append(item)
  1001. targetNamespace = getattr(item, 'targetNamespace', self.parent().targetNamespace)
  1002. if not self.data.has_key(targetNamespace):
  1003. self.data[targetNamespace] = {}
  1004. self.data[targetNamespace][key] = item
  1005. def __isSequence(self, key):
  1006. return (type(key) in (types.TupleType,types.ListType) and len(key) == 2)
  1007. def keys(self):
  1008. keys = []
  1009. for tns in self.data.keys():
  1010. keys.append(map(lambda i: (tns,self._func(i)), self.data[tns].values()))
  1011. return keys
  1012. def items(self):
  1013. return map(lambda i: (self._func(i), i), self.list)
  1014. def values(self):
  1015. return self.list
  1016. # This is a runtime guerilla patch for pulldom (used by minidom) so
  1017. # that xml namespace declaration attributes are not lost in parsing.
  1018. # We need them to do correct QName linking for XML Schema and WSDL.
  1019. # The patch has been submitted to SF for the next Python version.
  1020. from xml.dom.pulldom import PullDOM, START_ELEMENT
  1021. if 1:
  1022. def startPrefixMapping(self, prefix, uri):
  1023. if not hasattr(self, '_xmlns_attrs'):
  1024. self._xmlns_attrs = []
  1025. self._xmlns_attrs.append((prefix or 'xmlns', uri))
  1026. self._ns_contexts.append(self._current_context.copy())
  1027. self._current_context[uri] = prefix or ''
  1028. PullDOM.startPrefixMapping = startPrefixMapping
  1029. def startElementNS(self, name, tagName , attrs):
  1030. # Retrieve xml namespace declaration attributes.
  1031. xmlns_uri = 'http://www.w3.org/2000/xmlns/'
  1032. xmlns_attrs = getattr(self, '_xmlns_attrs', None)
  1033. if xmlns_attrs is not None:
  1034. for aname, value in xmlns_attrs:
  1035. attrs._attrs[(xmlns_uri, aname)] = value
  1036. self._xmlns_attrs = []
  1037. uri, localname = name
  1038. if uri:
  1039. # When using namespaces, the reader may or may not
  1040. # provide us with the original name. If not, create
  1041. # *a* valid tagName from the current context.
  1042. if tagName is None:
  1043. prefix = self._current_context[uri]
  1044. if prefix:
  1045. tagName = prefix + ":" + localname
  1046. else:
  1047. tagName = localname
  1048. if self.document:
  1049. node = self.document.createElementNS(uri, tagName)
  1050. else:
  1051. node = self.buildDocument(uri, tagName)
  1052. else:
  1053. # When the tagname is not prefixed, it just appears as
  1054. # localname
  1055. if self.document:
  1056. node = self.document.createElement(localname)
  1057. else:
  1058. node = self.buildDocument(None, localname)
  1059. for aname,value in attrs.items():
  1060. a_uri, a_localname = aname
  1061. if a_uri == xmlns_uri:
  1062. if a_localname == 'xmlns':
  1063. qname = a_localname
  1064. else:
  1065. qname = 'xmlns:' + a_localname
  1066. attr = self.document.createAttributeNS(a_uri, qname)
  1067. node.setAttributeNodeNS(attr)
  1068. elif a_uri:
  1069. prefix = self._current_context[a_uri]
  1070. if prefix:
  1071. qname = prefix + ":" + a_localname
  1072. else:
  1073. qname = a_localname
  1074. attr = self.document.createAttributeNS(a_uri, qname)
  1075. node.setAttributeNodeNS(attr)
  1076. else:
  1077. attr = self.document.createAttribute(a_localname)
  1078. node.setAttributeNode(attr)
  1079. attr.value = value
  1080. self.lastEvent[1] = [(START_ELEMENT, node), None]
  1081. self.lastEvent = self.lastEvent[1]
  1082. self.push(node)
  1083. PullDOM.startElementNS = startElementNS
  1084. #
  1085. # This is a runtime guerilla patch for minidom so
  1086. # that xmlns prefixed attributes dont raise AttributeErrors
  1087. # during cloning.
  1088. #
  1089. # Namespace declarations can appear in any start-tag, must look for xmlns
  1090. # prefixed attribute names during cloning.
  1091. #
  1092. # key (attr.namespaceURI, tag)
  1093. # ('http://www.w3.org/2000/xmlns/', u'xsd') <xml.dom.minidom.Attr instance at 0x82227c4>
  1094. # ('http://www.w3.org/2000/xmlns/', 'xmlns') <xml.dom.minidom.Attr instance at 0x8414b3c>
  1095. #
  1096. # xml.dom.minidom.Attr.nodeName = xmlns:xsd
  1097. # xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema
  1098. if 1:
  1099. def _clone_node(node, deep, newOwnerDocument):
  1100. """
  1101. Clone a node and give it the new owner document.
  1102. Called by Node.cloneNode and Document.importNode
  1103. """
  1104. if node.ownerDocument.isSameNode(newOwnerDocument):
  1105. operation = xml.dom.UserDataHandler.NODE_CLONED
  1106. else:
  1107. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  1108. if node.nodeType == xml.dom.minidom.Node.ELEMENT_NODE:
  1109. clone = newOwnerDocument.createElementNS(node.namespaceURI,
  1110. node.nodeName)
  1111. for attr in node.attributes.values():
  1112. clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
  1113. prefix, tag = xml.dom.minidom._nssplit(attr.nodeName)
  1114. if prefix == 'xmlns':
  1115. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  1116. elif prefix:
  1117. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  1118. else:
  1119. a = clone.getAttributeNodeNS(attr.namespaceURI, attr.nodeName)
  1120. a.specified = attr.specified
  1121. if deep:
  1122. for child in node.childNodes:
  1123. c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
  1124. clone.appendChild(c)
  1125. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE:
  1126. clone = newOwnerDocument.createDocumentFragment()
  1127. if deep:
  1128. for child in node.childNodes:
  1129. c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
  1130. clone.appendChild(c)
  1131. elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE:
  1132. clone = newOwnerDocument.createTextNode(node.data)
  1133. elif node.nodeType == xml.dom.minidom.Node.CDATA_SECTION_NODE:
  1134. clone = newOwnerDocument.createCDATASection(node.data)
  1135. elif node.nodeType == xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE:
  1136. clone = newOwnerDocument.createProcessingInstruction(node.target,
  1137. node.data)
  1138. elif node.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
  1139. clone = newOwnerDocument.createComment(node.data)
  1140. elif node.nodeType == xml.dom.minidom.Node.ATTRIBUTE_NODE:
  1141. clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
  1142. node.nodeName)
  1143. clone.specified = True
  1144. clone.value = node.value
  1145. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_TYPE_NODE:
  1146. assert node.ownerDocument is not newOwnerDocument
  1147. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  1148. clone = newOwnerDocument.implementation.createDocumentType(
  1149. node.name, node.publicId, node.systemId)
  1150. clone.ownerDocument = newOwnerDocument
  1151. if deep:
  1152. clone.entities._seq = []
  1153. clone.notations._seq = []
  1154. for n in node.notations._seq:
  1155. notation = xml.dom.minidom.Notation(n.nodeName, n.publicId, n.systemId)
  1156. notation.ownerDocument = newOwnerDocument
  1157. clone.notations._seq.append(notation)
  1158. if hasattr(n, '_call_user_data_handler'):
  1159. n._call_user_data_handler(operation, n, notation)
  1160. for e in node.entities._seq:
  1161. entity = xml.dom.minidom.Entity(e.nodeName, e.publicId, e.systemId,
  1162. e.notationName)
  1163. entity.actualEncoding = e.actualEncoding
  1164. entity.encoding = e.encoding
  1165. entity.version = e.version
  1166. entity.ownerDocument = newOwnerDocument
  1167. clone.entities._seq.append(entity)
  1168. if hasattr(e, '_call_user_data_handler'):
  1169. e._call_user_data_handler(operation, n, entity)
  1170. else:
  1171. # Note the cloning of Document and DocumentType nodes is
  1172. # implemenetation specific. minidom handles those cases
  1173. # directly in the cloneNode() methods.
  1174. raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
  1175. # Check for _call_user_data_handler() since this could conceivably
  1176. # used with other DOM implementations (one of the FourThought
  1177. # DOMs, perhaps?).
  1178. if hasattr(node, '_call_user_data_handler'):
  1179. node._call_user_data_handler(operation, node, clone)
  1180. return clone
  1181. xml.dom.minidom._clone_node = _clone_node