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.
 
 
 

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