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.
 
 
 

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