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.
 
 
 

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