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.
 
 
 

765 lines
28 KiB

  1. # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
  2. #
  3. # This software is subject to the provisions of the Zope Public License,
  4. # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
  5. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  6. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  7. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  8. # FOR A PARTICULAR PURPOSE.
  9. ident = "$Id$"
  10. from string import join, strip, split
  11. from UserDict import UserDict
  12. from StringIO import StringIO
  13. import xml.dom.minidom, weakref
  14. import string, httplib, smtplib, urllib, socket
  15. from TimeoutSocket import TimeoutSocket, TimeoutError
  16. from StringIO import StringIO
  17. from urlparse import urlparse
  18. from httplib import HTTPConnection, HTTPSConnection
  19. from exceptions import Exception
  20. class RecursionError(Exception):
  21. """Used to indicate a HTTP redirect recursion."""
  22. pass
  23. class HTTPResponse:
  24. """Captures the information in an HTTP response message."""
  25. def __init__(self, response):
  26. self.status = response.status
  27. self.reason = response.reason
  28. self.headers = response.msg
  29. self.body = response.read() or None
  30. response.close()
  31. class TimeoutHTTP(HTTPConnection):
  32. """A custom http connection object that supports socket timeout."""
  33. def __init__(self, host, port=None, timeout=20):
  34. HTTPConnection.__init__(self, host, port)
  35. self.timeout = timeout
  36. def connect(self):
  37. self.sock = TimeoutSocket(self.timeout)
  38. self.sock.connect((self.host, self.port))
  39. class TimeoutHTTPS(HTTPSConnection):
  40. """A custom https object that supports socket timeout. Note that this
  41. is not really complete. The builtin SSL support in the Python socket
  42. module requires a real socket (type) to be passed in to be hooked to
  43. SSL. That means our fake socket won't work and our timeout hacks are
  44. bypassed for send and recv calls. Since our hack _is_ in place at
  45. connect() time, it should at least provide some timeout protection."""
  46. def __init__(self, host, port=None, timeout=20, **kwargs):
  47. HTTPSConnection.__init__(self, str(host), port, **kwargs)
  48. self.timeout = timeout
  49. def connect(self):
  50. sock = TimeoutSocket(self.timeout)
  51. sock.connect((self.host, self.port))
  52. realsock = getattr(sock.sock, '_sock', sock.sock)
  53. ssl = socket.ssl(realsock, self.key_file, self.cert_file)
  54. self.sock = httplib.FakeSocket(sock, ssl)
  55. def urlopen(url, timeout=20, redirects=None):
  56. """A minimal urlopen replacement hack that supports timeouts for http.
  57. Note that this supports GET only."""
  58. scheme, host, path, params, query, frag = urlparse(url)
  59. if not scheme in ('http', 'https'):
  60. return urllib.urlopen(url)
  61. if params: path = '%s;%s' % (path, params)
  62. if query: path = '%s?%s' % (path, query)
  63. if frag: path = '%s#%s' % (path, frag)
  64. if scheme == 'https':
  65. # If ssl is not compiled into Python, you will not get an exception
  66. # until a conn.endheaders() call. We need to know sooner, so use
  67. # getattr.
  68. if hasattr(socket, 'ssl'):
  69. conn = TimeoutHTTPS(host, None, timeout)
  70. else:
  71. import M2Crypto
  72. ctx = M2Crypto.SSL.Context()
  73. ctx.set_session_timeout(timeout)
  74. conn = M2Crypto.httpslib.HTTPSConnection(host, ssl_context=ctx)
  75. #conn.set_debuglevel(1)
  76. else:
  77. conn = TimeoutHTTP(host, None, timeout)
  78. conn.putrequest('GET', path)
  79. conn.putheader('Connection', 'close')
  80. conn.endheaders()
  81. response = None
  82. while 1:
  83. response = conn.getresponse()
  84. if response.status != 100:
  85. break
  86. conn._HTTPConnection__state = httplib._CS_REQ_SENT
  87. conn._HTTPConnection__response = None
  88. status = response.status
  89. # If we get an HTTP redirect, we will follow it automatically.
  90. if status >= 300 and status < 400:
  91. location = response.msg.getheader('location')
  92. if location is not None:
  93. response.close()
  94. if redirects is not None and redirects.has_key(location):
  95. raise RecursionError(
  96. 'Circular HTTP redirection detected.'
  97. )
  98. if redirects is None:
  99. redirects = {}
  100. redirects[location] = 1
  101. return urlopen(location, timeout, redirects)
  102. raise HTTPResponse(response)
  103. if not (status >= 200 and status < 300):
  104. raise HTTPResponse(response)
  105. body = StringIO(response.read())
  106. response.close()
  107. return body
  108. class DOM:
  109. """The DOM singleton defines a number of XML related constants and
  110. provides a number of utility methods for DOM related tasks. It
  111. also provides some basic abstractions so that the rest of the
  112. package need not care about actual DOM implementation in use."""
  113. # Namespace stuff related to the SOAP specification.
  114. NS_SOAP_ENV_1_1 = 'http://schemas.xmlsoap.org/soap/envelope/'
  115. NS_SOAP_ENC_1_1 = 'http://schemas.xmlsoap.org/soap/encoding/'
  116. NS_SOAP_ENV_1_2 = 'http://www.w3.org/2001/06/soap-envelope'
  117. NS_SOAP_ENC_1_2 = 'http://www.w3.org/2001/06/soap-encoding'
  118. NS_SOAP_ENV_ALL = (NS_SOAP_ENV_1_1, NS_SOAP_ENV_1_2)
  119. NS_SOAP_ENC_ALL = (NS_SOAP_ENC_1_1, NS_SOAP_ENC_1_2)
  120. NS_SOAP_ENV = NS_SOAP_ENV_1_1
  121. NS_SOAP_ENC = NS_SOAP_ENC_1_1
  122. _soap_uri_mapping = {
  123. NS_SOAP_ENV_1_1 : '1.1',
  124. NS_SOAP_ENV_1_2 : '1.2',
  125. }
  126. SOAP_ACTOR_NEXT_1_1 = 'http://schemas.xmlsoap.org/soap/actor/next'
  127. SOAP_ACTOR_NEXT_1_2 = 'http://www.w3.org/2001/06/soap-envelope/actor/next'
  128. SOAP_ACTOR_NEXT_ALL = (SOAP_ACTOR_NEXT_1_1, SOAP_ACTOR_NEXT_1_2)
  129. def SOAPUriToVersion(self, uri):
  130. """Return the SOAP version related to an envelope uri."""
  131. value = self._soap_uri_mapping.get(uri)
  132. if value is not None:
  133. return value
  134. raise ValueError(
  135. 'Unsupported SOAP envelope uri: %s' % uri
  136. )
  137. def GetSOAPEnvUri(self, version):
  138. """Return the appropriate SOAP envelope uri for a given
  139. human-friendly SOAP version string (e.g. '1.1')."""
  140. attrname = 'NS_SOAP_ENV_%s' % join(split(version, '.'), '_')
  141. value = getattr(self, attrname, None)
  142. if value is not None:
  143. return value
  144. raise ValueError(
  145. 'Unsupported SOAP version: %s' % version
  146. )
  147. def GetSOAPEncUri(self, version):
  148. """Return the appropriate SOAP encoding uri for a given
  149. human-friendly SOAP version string (e.g. '1.1')."""
  150. attrname = 'NS_SOAP_ENC_%s' % join(split(version, '.'), '_')
  151. value = getattr(self, attrname, None)
  152. if value is not None:
  153. return value
  154. raise ValueError(
  155. 'Unsupported SOAP version: %s' % version
  156. )
  157. def GetSOAPActorNextUri(self, version):
  158. """Return the right special next-actor uri for a given
  159. human-friendly SOAP version string (e.g. '1.1')."""
  160. attrname = 'SOAP_ACTOR_NEXT_%s' % join(split(version, '.'), '_')
  161. value = getattr(self, attrname, None)
  162. if value is not None:
  163. return value
  164. raise ValueError(
  165. 'Unsupported SOAP version: %s' % version
  166. )
  167. # Namespace stuff related to XML Schema.
  168. NS_XSD_99 = 'http://www.w3.org/1999/XMLSchema'
  169. NS_XSI_99 = 'http://www.w3.org/1999/XMLSchema-instance'
  170. NS_XSD_00 = 'http://www.w3.org/2000/10/XMLSchema'
  171. NS_XSI_00 = 'http://www.w3.org/2000/10/XMLSchema-instance'
  172. NS_XSD_01 = 'http://www.w3.org/2001/XMLSchema'
  173. NS_XSI_01 = 'http://www.w3.org/2001/XMLSchema-instance'
  174. NS_XSD_ALL = (NS_XSD_99, NS_XSD_00, NS_XSD_01)
  175. NS_XSI_ALL = (NS_XSI_99, NS_XSI_00, NS_XSI_01)
  176. NS_XSD = NS_XSD_01
  177. NS_XSI = NS_XSI_01
  178. _xsd_uri_mapping = {
  179. NS_XSD_99 : NS_XSI_99,
  180. NS_XSD_00 : NS_XSI_00,
  181. NS_XSD_01 : NS_XSI_01,
  182. }
  183. for key, value in _xsd_uri_mapping.items():
  184. _xsd_uri_mapping[value] = key
  185. def InstanceUriForSchemaUri(self, uri):
  186. """Return the appropriate matching XML Schema instance uri for
  187. the given XML Schema namespace uri."""
  188. return self._xsd_uri_mapping.get(uri)
  189. def SchemaUriForInstanceUri(self, uri):
  190. """Return the appropriate matching XML Schema namespace uri for
  191. the given XML Schema instance namespace uri."""
  192. return self._xsd_uri_mapping.get(uri)
  193. # Namespace stuff related to WSDL.
  194. NS_WSDL_1_1 = 'http://schemas.xmlsoap.org/wsdl/'
  195. NS_WSDL_ALL = (NS_WSDL_1_1,)
  196. NS_WSDL = NS_WSDL_1_1
  197. NS_SOAP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/soap/'
  198. NS_HTTP_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/http/'
  199. NS_MIME_BINDING_1_1 = 'http://schemas.xmlsoap.org/wsdl/mime/'
  200. NS_SOAP_BINDING_ALL = (NS_SOAP_BINDING_1_1,)
  201. NS_HTTP_BINDING_ALL = (NS_HTTP_BINDING_1_1,)
  202. NS_MIME_BINDING_ALL = (NS_MIME_BINDING_1_1,)
  203. NS_SOAP_BINDING = NS_SOAP_BINDING_1_1
  204. NS_HTTP_BINDING = NS_HTTP_BINDING_1_1
  205. NS_MIME_BINDING = NS_MIME_BINDING_1_1
  206. NS_SOAP_HTTP_1_1 = 'http://schemas.xmlsoap.org/soap/http'
  207. NS_SOAP_HTTP_ALL = (NS_SOAP_HTTP_1_1,)
  208. NS_SOAP_HTTP = NS_SOAP_HTTP_1_1
  209. _wsdl_uri_mapping = {
  210. NS_WSDL_1_1 : '1.1',
  211. }
  212. def WSDLUriToVersion(self, uri):
  213. """Return the WSDL version related to a WSDL namespace uri."""
  214. value = self._wsdl_uri_mapping.get(uri)
  215. if value is not None:
  216. return value
  217. raise ValueError(
  218. 'Unsupported SOAP envelope uri: %s' % uri
  219. )
  220. def GetWSDLUri(self, version):
  221. attr = 'NS_WSDL_%s' % join(split(version, '.'), '_')
  222. value = getattr(self, attr, None)
  223. if value is not None:
  224. return value
  225. raise ValueError(
  226. 'Unsupported WSDL version: %s' % version
  227. )
  228. def GetWSDLSoapBindingUri(self, version):
  229. attr = 'NS_SOAP_BINDING_%s' % join(split(version, '.'), '_')
  230. value = getattr(self, attr, None)
  231. if value is not None:
  232. return value
  233. raise ValueError(
  234. 'Unsupported WSDL version: %s' % version
  235. )
  236. def GetWSDLHttpBindingUri(self, version):
  237. attr = 'NS_HTTP_BINDING_%s' % join(split(version, '.'), '_')
  238. value = getattr(self, attr, None)
  239. if value is not None:
  240. return value
  241. raise ValueError(
  242. 'Unsupported WSDL version: %s' % version
  243. )
  244. def GetWSDLMimeBindingUri(self, version):
  245. attr = 'NS_MIME_BINDING_%s' % join(split(version, '.'), '_')
  246. value = getattr(self, attr, None)
  247. if value is not None:
  248. return value
  249. raise ValueError(
  250. 'Unsupported WSDL version: %s' % version
  251. )
  252. def GetWSDLHttpTransportUri(self, version):
  253. attr = 'NS_SOAP_HTTP_%s' % join(split(version, '.'), '_')
  254. value = getattr(self, attr, None)
  255. if value is not None:
  256. return value
  257. raise ValueError(
  258. 'Unsupported WSDL version: %s' % version
  259. )
  260. # Other xml namespace constants.
  261. NS_XMLNS = 'http://www.w3.org/2000/xmlns/'
  262. def isElement(self, node, name, nsuri=None):
  263. """Return true if the given node is an element with the given
  264. name and optional namespace uri."""
  265. if node.nodeType == node.ELEMENT_NODE:
  266. return 0
  267. return node.localName == name and \
  268. (nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))
  269. def getElement(self, node, name, nsuri=None, default=join):
  270. """Return the first child of node with a matching name and
  271. namespace uri, or the default if one is provided."""
  272. nsmatch = self.nsUriMatch
  273. ELEMENT_NODE = node.ELEMENT_NODE
  274. for child in node.childNodes:
  275. if child.nodeType == ELEMENT_NODE:
  276. if ((child.localName == name or name is None) and
  277. (nsuri is None or nsmatch(child.namespaceURI, nsuri))
  278. ):
  279. return child
  280. if default is not join:
  281. return default
  282. raise KeyError, name
  283. def getElementById(self, node, id, default=join):
  284. """Return the first child of node matching an id reference."""
  285. attrget = self.getAttr
  286. ELEMENT_NODE = node.ELEMENT_NODE
  287. for child in node.childNodes:
  288. if child.nodeType == ELEMENT_NODE:
  289. if attrget(child, 'id') == id:
  290. return child
  291. if default is not join:
  292. return default
  293. raise KeyError, name
  294. def getMappingById(self, document, depth=None, element=None,
  295. mapping=None, level=1):
  296. """Create an id -> element mapping of those elements within a
  297. document that define an id attribute. The depth of the search
  298. may be controlled by using the (1-based) depth argument."""
  299. if document is not None:
  300. element = document.documentElement
  301. mapping = {}
  302. attr = element._attrs.get('id', None)
  303. if attr is not None:
  304. mapping[attr.value] = element
  305. if depth is None or depth > level:
  306. level = level + 1
  307. ELEMENT_NODE = element.ELEMENT_NODE
  308. for child in element.childNodes:
  309. if child.nodeType == ELEMENT_NODE:
  310. self.getMappingById(None, depth, child, mapping, level)
  311. return mapping
  312. def getElements(self, node, name, nsuri=None):
  313. """Return a sequence of the child elements of the given node that
  314. match the given name and optional namespace uri."""
  315. nsmatch = self.nsUriMatch
  316. result = []
  317. ELEMENT_NODE = node.ELEMENT_NODE
  318. for child in node.childNodes:
  319. if child.nodeType == ELEMENT_NODE:
  320. if ((child.localName == name or name is None) and (
  321. (nsuri is None) or nsmatch(child.namespaceURI, nsuri))):
  322. result.append(child)
  323. return result
  324. def hasAttr(self, node, name, nsuri=None):
  325. """Return true if element has attribute with the given name and
  326. optional nsuri. If nsuri is not specified, returns true if an
  327. attribute exists with the given name with any namespace."""
  328. if nsuri is None:
  329. if node._attrs.has_key(name):
  330. return 1
  331. for item in node._attrsNS.keys():
  332. if item[1] == name:
  333. return 1
  334. return 0
  335. return node.attrsNS.has_key((nsuri, name))
  336. def getAttr(self, node, name, nsuri=None, default=join):
  337. """Return the value of the attribute named 'name' with the
  338. optional nsuri, or the default if one is specified. If
  339. nsuri is not specified, an attribute that matches the
  340. given name will be returned regardless of namespace."""
  341. if nsuri is None:
  342. result = node._attrs.get(name, None)
  343. if result is None:
  344. for item in node._attrsNS.keys():
  345. if item[1] == name:
  346. result = node._attrsNS[item]
  347. break
  348. else:
  349. result = node._attrsNS.get((nsuri, name), None)
  350. if result is not None:
  351. return result.value
  352. if default is not join:
  353. return default
  354. return ''
  355. def getElementText(self, node, preserve_ws=None):
  356. """Return the text value of an xml element node. Leading and trailing
  357. whitespace is stripped from the value unless the preserve_ws flag
  358. is passed with a true value."""
  359. result = []
  360. for child in node.childNodes:
  361. nodetype = child.nodeType
  362. if nodetype == child.TEXT_NODE or \
  363. nodetype == child.CDATA_SECTION_NODE:
  364. result.append(child.nodeValue)
  365. value = join(result, '')
  366. if preserve_ws is None:
  367. value = strip(value)
  368. return value
  369. def findNamespaceURI(self, prefix, node):
  370. """Find a namespace uri given a prefix and a context node."""
  371. attrkey = (self.NS_XMLNS, prefix)
  372. DOCUMENT_NODE = node.DOCUMENT_NODE
  373. ELEMENT_NODE = node.ELEMENT_NODE
  374. while 1:
  375. if node.nodeType != ELEMENT_NODE:
  376. node = node.parentNode
  377. continue
  378. result = node._attrsNS.get(attrkey, None)
  379. if result is not None:
  380. return result.value
  381. if hasattr(node, '__imported__'):
  382. raise DOMException('Value for prefix %s not found.' % prefix)
  383. node = node.parentNode
  384. if node.nodeType == DOCUMENT_NODE:
  385. raise DOMException('Value for prefix %s not found.' % prefix)
  386. def findDefaultNS(self, node):
  387. """Return the current default namespace uri for the given node."""
  388. attrkey = (self.NS_XMLNS, 'xmlns')
  389. DOCUMENT_NODE = node.DOCUMENT_NODE
  390. ELEMENT_NODE = node.ELEMENT_NODE
  391. while 1:
  392. if node.nodeType != ELEMENT_NODE:
  393. node = node.parentNode
  394. continue
  395. result = node._attrsNS.get(attrkey, None)
  396. if result is not None:
  397. return result.value
  398. if hasattr(node, '__imported__'):
  399. raise DOMException('Cannot determine default namespace.')
  400. node = node.parentNode
  401. if node.nodeType == DOCUMENT_NODE:
  402. raise DOMException('Cannot determine default namespace.')
  403. def findTargetNS(self, node):
  404. """Return the defined target namespace uri for the given node."""
  405. attrget = self.getAttr
  406. attrkey = (self.NS_XMLNS, 'xmlns')
  407. DOCUMENT_NODE = node.DOCUMENT_NODE
  408. ELEMENT_NODE = node.ELEMENT_NODE
  409. while 1:
  410. if node.nodeType != ELEMENT_NODE:
  411. node = node.parentNode
  412. continue
  413. result = attrget(node, 'targetNamespace', default=None)
  414. if result is not None:
  415. return result
  416. node = node.parentNode
  417. if node.nodeType == DOCUMENT_NODE:
  418. raise DOMException('Cannot determine target namespace.')
  419. def getTypeRef(self, element):
  420. """Return (namespaceURI, name) for a type attribue of the given
  421. element, or None if the element does not have a type attribute."""
  422. typeattr = self.getAttr(element, 'type', default=None)
  423. if typeattr is None:
  424. return None
  425. parts = typeattr.split(':', 1)
  426. if len(parts) == 2:
  427. nsuri = self.findNamespaceURI(parts[0], element)
  428. else:
  429. nsuri = self.findDefaultNS(element)
  430. return (nsuri, parts[1])
  431. def importNode(self, document, node, deep=0):
  432. """Implements (well enough for our purposes) DOM node import."""
  433. nodetype = node.nodeType
  434. if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
  435. raise DOMException('Illegal node type for importNode')
  436. if nodetype == node.ENTITY_REFERENCE_NODE:
  437. deep = 0
  438. clone = node.cloneNode(deep)
  439. self._setOwnerDoc(document, clone)
  440. clone.__imported__ = 1
  441. return clone
  442. def _setOwnerDoc(self, document, node):
  443. node.ownerDocument = document
  444. for child in node.childNodes:
  445. self._setOwnerDoc(document, child)
  446. def nsUriMatch(self, value, wanted, strict=0, tt=type(())):
  447. """Return a true value if two namespace uri values match."""
  448. if value == wanted or (type(wanted) is tt) and value in wanted:
  449. return 1
  450. if not strict:
  451. wanted = type(wanted) is tt and wanted or (wanted,)
  452. value = value[-1:] != '/' and value or value[:-1]
  453. for item in wanted:
  454. if item == value or item[:-1] == value:
  455. return 1
  456. return 0
  457. def createDocument(self, nsuri, qname, doctype=None):
  458. """Create a new writable DOM document object."""
  459. impl = xml.dom.minidom.getDOMImplementation()
  460. return impl.createDocument(nsuri, qname, doctype)
  461. def loadDocument(self, data):
  462. """Load an xml file from a file-like object and return a DOM
  463. document instance."""
  464. return xml.dom.minidom.parse(data)
  465. def loadFromURL(self, url):
  466. """Load an xml file from a URL and return a DOM document."""
  467. file = urlopen(url)
  468. try: result = self.loadDocument(file)
  469. finally: file.close()
  470. return result
  471. class DOMException(Exception):
  472. pass
  473. DOM = DOM()
  474. class Collection(UserDict):
  475. """Helper class for maintaining ordered named collections."""
  476. default = lambda self,k: k.name
  477. def __init__(self, parent, key=None):
  478. UserDict.__init__(self)
  479. self.parent = weakref.ref(parent)
  480. self.list = []
  481. self._func = key or self.default
  482. def __getitem__(self, key):
  483. if type(key) is type(1):
  484. return self.list[key]
  485. return self.data[key]
  486. def __setitem__(self, key, item):
  487. item.parent = weakref.ref(self)
  488. self.list.append(item)
  489. self.data[key] = item
  490. def keys(self):
  491. return map(lambda i: self._func(i), self.list)
  492. def items(self):
  493. return map(lambda i: (self._func(i), i), self.list)
  494. def values(self):
  495. return self.list
  496. # This is a runtime guerilla patch for pulldom (used by minidom) so
  497. # that xml namespace declaration attributes are not lost in parsing.
  498. # We need them to do correct QName linking for XML Schema and WSDL.
  499. # The patch has been submitted to SF for the next Python version.
  500. from xml.dom.pulldom import PullDOM, START_ELEMENT
  501. if 1:
  502. def startPrefixMapping(self, prefix, uri):
  503. if not hasattr(self, '_xmlns_attrs'):
  504. self._xmlns_attrs = []
  505. self._xmlns_attrs.append((prefix or 'xmlns', uri))
  506. self._ns_contexts.append(self._current_context.copy())
  507. self._current_context[uri] = prefix or ''
  508. PullDOM.startPrefixMapping = startPrefixMapping
  509. def startElementNS(self, name, tagName , attrs):
  510. # Retrieve xml namespace declaration attributes.
  511. xmlns_uri = 'http://www.w3.org/2000/xmlns/'
  512. xmlns_attrs = getattr(self, '_xmlns_attrs', None)
  513. if xmlns_attrs is not None:
  514. for aname, value in xmlns_attrs:
  515. attrs._attrs[(xmlns_uri, aname)] = value
  516. self._xmlns_attrs = []
  517. uri, localname = name
  518. if uri:
  519. # When using namespaces, the reader may or may not
  520. # provide us with the original name. If not, create
  521. # *a* valid tagName from the current context.
  522. if tagName is None:
  523. prefix = self._current_context[uri]
  524. if prefix:
  525. tagName = prefix + ":" + localname
  526. else:
  527. tagName = localname
  528. if self.document:
  529. node = self.document.createElementNS(uri, tagName)
  530. else:
  531. node = self.buildDocument(uri, tagName)
  532. else:
  533. # When the tagname is not prefixed, it just appears as
  534. # localname
  535. if self.document:
  536. node = self.document.createElement(localname)
  537. else:
  538. node = self.buildDocument(None, localname)
  539. for aname,value in attrs.items():
  540. a_uri, a_localname = aname
  541. if a_uri == xmlns_uri:
  542. if a_localname == 'xmlns':
  543. qname = a_localname
  544. else:
  545. qname = 'xmlns:' + a_localname
  546. attr = self.document.createAttributeNS(a_uri, qname)
  547. node.setAttributeNodeNS(attr)
  548. elif a_uri:
  549. prefix = self._current_context[a_uri]
  550. if prefix:
  551. qname = prefix + ":" + a_localname
  552. else:
  553. qname = a_localname
  554. attr = self.document.createAttributeNS(a_uri, qname)
  555. node.setAttributeNodeNS(attr)
  556. else:
  557. attr = self.document.createAttribute(a_localname)
  558. node.setAttributeNode(attr)
  559. attr.value = value
  560. self.lastEvent[1] = [(START_ELEMENT, node), None]
  561. self.lastEvent = self.lastEvent[1]
  562. self.push(node)
  563. PullDOM.startElementNS = startElementNS
  564. #
  565. # This is a runtime guerilla patch for minidom so
  566. # that xmlns prefixed attributes dont raise AttributeErrors
  567. # during cloning.
  568. #
  569. # Namespace declarations can appear in any start-tag, must look for xmlns
  570. # prefixed attribute names during cloning.
  571. #
  572. # key (attr.namespaceURI, tag)
  573. # ('http://www.w3.org/2000/xmlns/', u'xsd') <xml.dom.minidom.Attr instance at 0x82227c4>
  574. # ('http://www.w3.org/2000/xmlns/', 'xmlns') <xml.dom.minidom.Attr instance at 0x8414b3c>
  575. #
  576. # xml.dom.minidom.Attr.nodeName = xmlns:xsd
  577. # xml.dom.minidom.Attr.value = = http://www.w3.org/2001/XMLSchema
  578. if 1:
  579. def _clone_node(node, deep, newOwnerDocument):
  580. """
  581. Clone a node and give it the new owner document.
  582. Called by Node.cloneNode and Document.importNode
  583. """
  584. if node.ownerDocument.isSameNode(newOwnerDocument):
  585. operation = xml.dom.UserDataHandler.NODE_CLONED
  586. else:
  587. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  588. if node.nodeType == xml.dom.minidom.Node.ELEMENT_NODE:
  589. clone = newOwnerDocument.createElementNS(node.namespaceURI,
  590. node.nodeName)
  591. for attr in node.attributes.values():
  592. clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
  593. prefix, tag = xml.dom.minidom._nssplit(attr.nodeName)
  594. if prefix == 'xmlns':
  595. a = clone.getAttributeNodeNS(attr.namespaceURI, tag)
  596. else:
  597. a = clone.getAttributeNodeNS(attr.namespaceURI, attr.nodeName)
  598. a.specified = attr.specified
  599. if deep:
  600. for child in node.childNodes:
  601. c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
  602. clone.appendChild(c)
  603. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_FRAGMENT_NODE:
  604. clone = newOwnerDocument.createDocumentFragment()
  605. if deep:
  606. for child in node.childNodes:
  607. c = xml.dom.minidom._clone_node(child, deep, newOwnerDocument)
  608. clone.appendChild(c)
  609. elif node.nodeType == xml.dom.minidom.Node.TEXT_NODE:
  610. clone = newOwnerDocument.createTextNode(node.data)
  611. elif node.nodeType == xml.dom.minidom.Node.CDATA_SECTION_NODE:
  612. clone = newOwnerDocument.createCDATASection(node.data)
  613. elif node.nodeType == xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE:
  614. clone = newOwnerDocument.createProcessingInstruction(node.target,
  615. node.data)
  616. elif node.nodeType == xml.dom.minidom.Node.COMMENT_NODE:
  617. clone = newOwnerDocument.createComment(node.data)
  618. elif node.nodeType == xml.dom.minidom.Node.ATTRIBUTE_NODE:
  619. clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
  620. node.nodeName)
  621. clone.specified = True
  622. clone.value = node.value
  623. elif node.nodeType == xml.dom.minidom.Node.DOCUMENT_TYPE_NODE:
  624. assert node.ownerDocument is not newOwnerDocument
  625. operation = xml.dom.UserDataHandler.NODE_IMPORTED
  626. clone = newOwnerDocument.implementation.createDocumentType(
  627. node.name, node.publicId, node.systemId)
  628. clone.ownerDocument = newOwnerDocument
  629. if deep:
  630. clone.entities._seq = []
  631. clone.notations._seq = []
  632. for n in node.notations._seq:
  633. notation = xml.dom.minidom.Notation(n.nodeName, n.publicId, n.systemId)
  634. notation.ownerDocument = newOwnerDocument
  635. clone.notations._seq.append(notation)
  636. if hasattr(n, '_call_user_data_handler'):
  637. n._call_user_data_handler(operation, n, notation)
  638. for e in node.entities._seq:
  639. entity = xml.dom.minidom.Entity(e.nodeName, e.publicId, e.systemId,
  640. e.notationName)
  641. entity.actualEncoding = e.actualEncoding
  642. entity.encoding = e.encoding
  643. entity.version = e.version
  644. entity.ownerDocument = newOwnerDocument
  645. clone.entities._seq.append(entity)
  646. if hasattr(e, '_call_user_data_handler'):
  647. e._call_user_data_handler(operation, n, entity)
  648. else:
  649. # Note the cloning of Document and DocumentType nodes is
  650. # implemenetation specific. minidom handles those cases
  651. # directly in the cloneNode() methods.
  652. raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
  653. # Check for _call_user_data_handler() since this could conceivably
  654. # used with other DOM implementations (one of the FourThought
  655. # DOMs, perhaps?).
  656. if hasattr(node, '_call_user_data_handler'):
  657. node._call_user_data_handler(operation, node, clone)
  658. return clone
  659. xml.dom.minidom._clone_node = _clone_node