blob: 3025ed73194e5a8b6bb4c0a727a68cafc2c82240 [file] [log] [blame]
Fred Drake1f549022000-09-24 05:21:58 +00001"""\
Fred Drakef7cf40d2000-12-14 18:16:11 +00002minidom.py -- a lightweight DOM implementation.
Fred Drake55c38192000-06-29 19:39:57 +00003
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00004parse("foo.xml")
Paul Prescod623511b2000-07-21 22:05:49 +00005
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00006parseString("<foo><bar/></foo>")
Paul Prescod623511b2000-07-21 22:05:49 +00007
Fred Drake55c38192000-06-29 19:39:57 +00008Todo:
9=====
10 * convenience methods for getting elements and text.
11 * more testing
12 * bring some of the writer and linearizer code into conformance with this
13 interface
14 * SAX 2 namespaces
15"""
16
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000017import codecs
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000018import io
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019import xml.dom
Fred Drake55c38192000-06-29 19:39:57 +000020
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg
22from xml.dom.minicompat import *
23from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS
Fred Drake3ac6a092001-09-28 04:33:06 +000024
Martin v. Löwis787354c2003-01-25 15:28:29 +000025# This is used by the ID-cache invalidation checks; the list isn't
26# actually complete, since the nodes being checked will never be the
27# DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is
28# the node being added or removed, not the node being modified.)
29#
Thomas Wouters0e3f5912006-08-11 14:57:12 +000030_nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE,
31 xml.dom.Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis95700f72002-03-15 13:51:59 +000032
Fred Drake3ac6a092001-09-28 04:33:06 +000033
Thomas Wouters0e3f5912006-08-11 14:57:12 +000034class Node(xml.dom.Node):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000035 namespaceURI = None # this is non-null only for elements and attributes
Fred Drake575712e2001-09-28 20:25:45 +000036 parentNode = None
37 ownerDocument = None
Martin v. Löwis787354c2003-01-25 15:28:29 +000038 nextSibling = None
39 previousSibling = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +000040
Martin v. Löwis787354c2003-01-25 15:28:29 +000041 prefix = EMPTY_PREFIX # non-null only for NS elements and attributes
Fred Drake55c38192000-06-29 19:39:57 +000042
Jack Diederich4dafcc42006-11-28 19:15:13 +000043 def __bool__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +000044 return True
Fred Drake55c38192000-06-29 19:39:57 +000045
Martin v. Löwis7d650ca2002-06-30 15:05:00 +000046 def toxml(self, encoding = None):
47 return self.toprettyxml("", "", encoding)
Fred Drake55c38192000-06-29 19:39:57 +000048
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000049 def toprettyxml(self, indent="\t", newl="\n", encoding=None):
Martin v. Löwiscb67ea12001-03-31 16:30:40 +000050 # indent = the indentation string to prepend, per level
51 # newl = the newline string to append
Guido van Rossum55b15c92007-08-07 23:03:33 +000052 use_encoding = "utf-8" if encoding is None else encoding
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000053 writer = codecs.getwriter(use_encoding)(io.BytesIO())
Martin v. Löwis7d650ca2002-06-30 15:05:00 +000054 if self.nodeType == Node.DOCUMENT_NODE:
55 # Can pass encoding only to document, to put it into XML header
56 self.writexml(writer, "", indent, newl, encoding)
57 else:
58 self.writexml(writer, "", indent, newl)
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000059 if encoding is None:
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000060 return writer.stream.getvalue().decode(use_encoding)
Guido van Rossum3e1f85e2007-07-27 18:03:11 +000061 else:
Alexandre Vassalotti794652d2008-06-11 22:58:36 +000062 return writer.stream.getvalue()
Martin v. Löwis46fa39a2001-02-06 00:14:08 +000063
Fred Drake1f549022000-09-24 05:21:58 +000064 def hasChildNodes(self):
65 if self.childNodes:
Martin v. Löwis787354c2003-01-25 15:28:29 +000066 return True
Fred Drake1f549022000-09-24 05:21:58 +000067 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +000068 return False
69
70 def _get_childNodes(self):
71 return self.childNodes
Fred Drake55c38192000-06-29 19:39:57 +000072
Fred Drake1f549022000-09-24 05:21:58 +000073 def _get_firstChild(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +000074 if self.childNodes:
75 return self.childNodes[0]
Paul Prescod73678da2000-07-01 04:58:47 +000076
Fred Drake1f549022000-09-24 05:21:58 +000077 def _get_lastChild(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +000078 if self.childNodes:
79 return self.childNodes[-1]
Paul Prescod73678da2000-07-01 04:58:47 +000080
Fred Drake1f549022000-09-24 05:21:58 +000081 def insertBefore(self, newChild, refChild):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000082 if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
Fred Drakee50959a2001-12-06 04:32:18 +000083 for c in tuple(newChild.childNodes):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000084 self.insertBefore(c, refChild)
85 ### The DOM does not clearly specify what to return in this case
86 return newChild
Martin v. Löwis787354c2003-01-25 15:28:29 +000087 if newChild.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000088 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +000089 "%s cannot be child of %s" % (repr(newChild), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +000090 if newChild.parentNode is not None:
91 newChild.parentNode.removeChild(newChild)
Fred Drake4ccf4a12000-11-21 22:02:22 +000092 if refChild is None:
93 self.appendChild(newChild)
94 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +000095 try:
96 index = self.childNodes.index(refChild)
97 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000098 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +000099 if newChild.nodeType in _nodeTypes_with_children:
100 _clear_id_cache(self)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000101 self.childNodes.insert(index, newChild)
102 newChild.nextSibling = refChild
103 refChild.previousSibling = newChild
104 if index:
105 node = self.childNodes[index-1]
106 node.nextSibling = newChild
107 newChild.previousSibling = node
108 else:
109 newChild.previousSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000110 newChild.parentNode = self
Fred Drake4ccf4a12000-11-21 22:02:22 +0000111 return newChild
Fred Drake55c38192000-06-29 19:39:57 +0000112
Fred Drake1f549022000-09-24 05:21:58 +0000113 def appendChild(self, node):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000114 if node.nodeType == self.DOCUMENT_FRAGMENT_NODE:
Fred Drakee50959a2001-12-06 04:32:18 +0000115 for c in tuple(node.childNodes):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000116 self.appendChild(c)
117 ### The DOM does not clearly specify what to return in this case
118 return node
Martin v. Löwis787354c2003-01-25 15:28:29 +0000119 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000120 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000121 "%s cannot be child of %s" % (repr(node), repr(self)))
122 elif node.nodeType in _nodeTypes_with_children:
123 _clear_id_cache(self)
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000124 if node.parentNode is not None:
125 node.parentNode.removeChild(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000126 _append_child(self, node)
Fred Drake13a30692000-10-09 20:04:16 +0000127 node.nextSibling = None
Paul Prescod73678da2000-07-01 04:58:47 +0000128 return node
129
Fred Drake1f549022000-09-24 05:21:58 +0000130 def replaceChild(self, newChild, oldChild):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000131 if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
132 refChild = oldChild.nextSibling
133 self.removeChild(oldChild)
134 return self.insertBefore(newChild, refChild)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000135 if newChild.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000136 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000137 "%s cannot be child of %s" % (repr(newChild), repr(self)))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000138 if newChild is oldChild:
139 return
Andrew M. Kuchling841d25e2005-11-22 19:03:16 +0000140 if newChild.parentNode is not None:
141 newChild.parentNode.removeChild(newChild)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000142 try:
143 index = self.childNodes.index(oldChild)
144 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000145 raise xml.dom.NotFoundErr()
Fred Drake4ccf4a12000-11-21 22:02:22 +0000146 self.childNodes[index] = newChild
Martin v. Löwis787354c2003-01-25 15:28:29 +0000147 newChild.parentNode = self
148 oldChild.parentNode = None
149 if (newChild.nodeType in _nodeTypes_with_children
150 or oldChild.nodeType in _nodeTypes_with_children):
151 _clear_id_cache(self)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000152 newChild.nextSibling = oldChild.nextSibling
153 newChild.previousSibling = oldChild.previousSibling
Martin v. Löwis156c3372000-12-28 18:40:56 +0000154 oldChild.nextSibling = None
Fred Drake4ccf4a12000-11-21 22:02:22 +0000155 oldChild.previousSibling = None
Martin v. Löwis156c3372000-12-28 18:40:56 +0000156 if newChild.previousSibling:
157 newChild.previousSibling.nextSibling = newChild
158 if newChild.nextSibling:
159 newChild.nextSibling.previousSibling = newChild
Fred Drake4ccf4a12000-11-21 22:02:22 +0000160 return oldChild
Paul Prescod73678da2000-07-01 04:58:47 +0000161
Fred Drake1f549022000-09-24 05:21:58 +0000162 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000163 try:
164 self.childNodes.remove(oldChild)
165 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000166 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000167 if oldChild.nextSibling is not None:
168 oldChild.nextSibling.previousSibling = oldChild.previousSibling
169 if oldChild.previousSibling is not None:
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000170 oldChild.previousSibling.nextSibling = oldChild.nextSibling
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000171 oldChild.nextSibling = oldChild.previousSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000172 if oldChild.nodeType in _nodeTypes_with_children:
173 _clear_id_cache(self)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000174
Martin v. Löwis787354c2003-01-25 15:28:29 +0000175 oldChild.parentNode = None
Fred Drake4ccf4a12000-11-21 22:02:22 +0000176 return oldChild
177
178 def normalize(self):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000179 L = []
180 for child in self.childNodes:
181 if child.nodeType == Node.TEXT_NODE:
182 data = child.data
183 if data and L and L[-1].nodeType == child.nodeType:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000184 # collapse text node
185 node = L[-1]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000186 node.data = node.data + child.data
Fred Drake4ccf4a12000-11-21 22:02:22 +0000187 node.nextSibling = child.nextSibling
188 child.unlink()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000189 elif data:
190 if L:
191 L[-1].nextSibling = child
192 child.previousSibling = L[-1]
193 else:
194 child.previousSibling = None
195 L.append(child)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000196 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000197 # empty text node; discard
198 child.unlink()
199 else:
200 if L:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000201 L[-1].nextSibling = child
202 child.previousSibling = L[-1]
Fred Drakef7cf40d2000-12-14 18:16:11 +0000203 else:
204 child.previousSibling = None
205 L.append(child)
206 if child.nodeType == Node.ELEMENT_NODE:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000207 child.normalize()
Christian Heimes05e8be12008-02-23 18:30:17 +0000208 if L:
209 L[-1].nextSibling = None
Fred Drakef7cf40d2000-12-14 18:16:11 +0000210 self.childNodes[:] = L
Paul Prescod73678da2000-07-01 04:58:47 +0000211
Fred Drake1f549022000-09-24 05:21:58 +0000212 def cloneNode(self, deep):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000213 return _clone_node(self, deep, self.ownerDocument or self)
Fred Drake55c38192000-06-29 19:39:57 +0000214
Martin v. Löwis787354c2003-01-25 15:28:29 +0000215 def isSupported(self, feature, version):
216 return self.ownerDocument.implementation.hasFeature(feature, version)
217
218 def _get_localName(self):
219 # Overridden in Element and Attr where localName can be Non-Null
220 return None
221
222 # Node interfaces from Level 3 (WD 9 April 2002)
Fred Drake25239772001-02-02 19:40:19 +0000223
224 def isSameNode(self, other):
225 return self is other
226
Martin v. Löwis787354c2003-01-25 15:28:29 +0000227 def getInterface(self, feature):
228 if self.isSupported(feature, None):
229 return self
230 else:
231 return None
232
233 # The "user data" functions use a dictionary that is only present
234 # if some user data has been set, so be careful not to assume it
235 # exists.
236
237 def getUserData(self, key):
238 try:
239 return self._user_data[key][0]
240 except (AttributeError, KeyError):
241 return None
242
243 def setUserData(self, key, data, handler):
244 old = None
245 try:
246 d = self._user_data
247 except AttributeError:
248 d = {}
249 self._user_data = d
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000250 if key in d:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000251 old = d[key][0]
252 if data is None:
253 # ignore handlers passed for None
254 handler = None
255 if old is not None:
256 del d[key]
257 else:
258 d[key] = (data, handler)
259 return old
260
261 def _call_user_data_handler(self, operation, src, dst):
262 if hasattr(self, "_user_data"):
Brett Cannon861fd6f2007-02-21 22:05:37 +0000263 for key, (data, handler) in list(self._user_data.items()):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000264 if handler is not None:
265 handler.handle(operation, key, data, src, dst)
266
Fred Drake25239772001-02-02 19:40:19 +0000267 # minidom-specific API:
268
Fred Drake1f549022000-09-24 05:21:58 +0000269 def unlink(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000270 self.parentNode = self.ownerDocument = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000271 if self.childNodes:
272 for child in self.childNodes:
273 child.unlink()
274 self.childNodes = NodeList()
Paul Prescod4221ff02000-10-13 20:11:42 +0000275 self.previousSibling = None
276 self.nextSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000277
278defproperty(Node, "firstChild", doc="First child node, or None.")
279defproperty(Node, "lastChild", doc="Last child node, or None.")
280defproperty(Node, "localName", doc="Namespace-local name of this node.")
281
282
283def _append_child(self, node):
284 # fast path with less checks; usable by DOM builders if careful
285 childNodes = self.childNodes
286 if childNodes:
287 last = childNodes[-1]
288 node.__dict__["previousSibling"] = last
289 last.__dict__["nextSibling"] = node
290 childNodes.append(node)
291 node.__dict__["parentNode"] = self
292
293def _in_document(node):
294 # return True iff node is part of a document tree
295 while node is not None:
296 if node.nodeType == Node.DOCUMENT_NODE:
297 return True
298 node = node.parentNode
299 return False
Fred Drake55c38192000-06-29 19:39:57 +0000300
Fred Drake1f549022000-09-24 05:21:58 +0000301def _write_data(writer, data):
Fred Drake55c38192000-06-29 19:39:57 +0000302 "Writes datachars to writer."
Martin v. Löwis787354c2003-01-25 15:28:29 +0000303 data = data.replace("&", "&amp;").replace("<", "&lt;")
304 data = data.replace("\"", "&quot;").replace(">", "&gt;")
Fred Drake55c38192000-06-29 19:39:57 +0000305 writer.write(data)
306
Martin v. Löwis787354c2003-01-25 15:28:29 +0000307def _get_elements_by_tagName_helper(parent, name, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000308 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000309 if node.nodeType == Node.ELEMENT_NODE and \
310 (name == "*" or node.tagName == name):
311 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000312 _get_elements_by_tagName_helper(node, name, rc)
Fred Drake55c38192000-06-29 19:39:57 +0000313 return rc
314
Martin v. Löwis787354c2003-01-25 15:28:29 +0000315def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000316 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000317 if node.nodeType == Node.ELEMENT_NODE:
Martin v. Löwised525fb2001-06-03 14:06:42 +0000318 if ((localName == "*" or node.localName == localName) and
Fred Drake1f549022000-09-24 05:21:58 +0000319 (nsURI == "*" or node.namespaceURI == nsURI)):
320 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000321 _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000322 return rc
Fred Drake55c38192000-06-29 19:39:57 +0000323
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000324class DocumentFragment(Node):
325 nodeType = Node.DOCUMENT_FRAGMENT_NODE
326 nodeName = "#document-fragment"
327 nodeValue = None
328 attributes = None
329 parentNode = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000330 _child_node_types = (Node.ELEMENT_NODE,
331 Node.TEXT_NODE,
332 Node.CDATA_SECTION_NODE,
333 Node.ENTITY_REFERENCE_NODE,
334 Node.PROCESSING_INSTRUCTION_NODE,
335 Node.COMMENT_NODE,
336 Node.NOTATION_NODE)
337
338 def __init__(self):
339 self.childNodes = NodeList()
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000340
341
Fred Drake55c38192000-06-29 19:39:57 +0000342class Attr(Node):
Fred Drake1f549022000-09-24 05:21:58 +0000343 nodeType = Node.ATTRIBUTE_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +0000344 attributes = None
345 ownerElement = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000346 specified = False
347 _is_id = False
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000348
Martin v. Löwis787354c2003-01-25 15:28:29 +0000349 _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE)
350
351 def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None,
352 prefix=None):
Fred Drake55c38192000-06-29 19:39:57 +0000353 # skip setattr for performance
Fred Drake4ccf4a12000-11-21 22:02:22 +0000354 d = self.__dict__
Fred Drake4ccf4a12000-11-21 22:02:22 +0000355 d["nodeName"] = d["name"] = qName
356 d["namespaceURI"] = namespaceURI
357 d["prefix"] = prefix
Martin v. Löwis787354c2003-01-25 15:28:29 +0000358 d['childNodes'] = NodeList()
359
360 # Add the single child node that represents the value of the attr
361 self.childNodes.append(Text())
362
Paul Prescod73678da2000-07-01 04:58:47 +0000363 # nodeValue and value are set elsewhere
Fred Drake55c38192000-06-29 19:39:57 +0000364
Martin v. Löwis787354c2003-01-25 15:28:29 +0000365 def _get_localName(self):
Alex Martelli0ee43512006-08-21 19:53:20 +0000366 if 'localName' in self.__dict__:
Guido van Rossum3e1f85e2007-07-27 18:03:11 +0000367 return self.__dict__['localName']
Martin v. Löwis787354c2003-01-25 15:28:29 +0000368 return self.nodeName.split(":", 1)[-1]
369
370 def _get_name(self):
371 return self.name
372
373 def _get_specified(self):
374 return self.specified
375
Fred Drake1f549022000-09-24 05:21:58 +0000376 def __setattr__(self, name, value):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000377 d = self.__dict__
Fred Drake1f549022000-09-24 05:21:58 +0000378 if name in ("value", "nodeValue"):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000379 d["value"] = d["nodeValue"] = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000380 d2 = self.childNodes[0].__dict__
381 d2["data"] = d2["nodeValue"] = value
382 if self.ownerElement is not None:
383 _clear_id_cache(self.ownerElement)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000384 elif name in ("name", "nodeName"):
385 d["name"] = d["nodeName"] = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000386 if self.ownerElement is not None:
387 _clear_id_cache(self.ownerElement)
Fred Drake55c38192000-06-29 19:39:57 +0000388 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000389 d[name] = value
Fred Drake55c38192000-06-29 19:39:57 +0000390
Martin v. Löwis995359c2003-01-26 08:59:32 +0000391 def _set_prefix(self, prefix):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000392 nsuri = self.namespaceURI
Martin v. Löwis995359c2003-01-26 08:59:32 +0000393 if prefix == "xmlns":
394 if nsuri and nsuri != XMLNS_NAMESPACE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000395 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000396 "illegal use of 'xmlns' prefix for the wrong namespace")
397 d = self.__dict__
398 d['prefix'] = prefix
399 if prefix is None:
400 newName = self.localName
401 else:
Martin v. Löwis995359c2003-01-26 08:59:32 +0000402 newName = "%s:%s" % (prefix, self.localName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000403 if self.ownerElement:
404 _clear_id_cache(self.ownerElement)
405 d['nodeName'] = d['name'] = newName
406
407 def _set_value(self, value):
408 d = self.__dict__
409 d['value'] = d['nodeValue'] = value
410 if self.ownerElement:
411 _clear_id_cache(self.ownerElement)
412 self.childNodes[0].data = value
413
414 def unlink(self):
415 # This implementation does not call the base implementation
416 # since most of that is not needed, and the expense of the
417 # method call is not warranted. We duplicate the removal of
418 # children, but that's all we needed from the base class.
419 elem = self.ownerElement
420 if elem is not None:
421 del elem._attrs[self.nodeName]
422 del elem._attrsNS[(self.namespaceURI, self.localName)]
423 if self._is_id:
424 self._is_id = False
425 elem._magic_id_nodes -= 1
426 self.ownerDocument._magic_id_count -= 1
427 for child in self.childNodes:
428 child.unlink()
429 del self.childNodes[:]
430
431 def _get_isId(self):
432 if self._is_id:
433 return True
434 doc = self.ownerDocument
435 elem = self.ownerElement
436 if doc is None or elem is None:
437 return False
438
439 info = doc._get_elem_info(elem)
440 if info is None:
441 return False
442 if self.namespaceURI:
443 return info.isIdNS(self.namespaceURI, self.localName)
444 else:
445 return info.isId(self.nodeName)
446
447 def _get_schemaType(self):
448 doc = self.ownerDocument
449 elem = self.ownerElement
450 if doc is None or elem is None:
451 return _no_type
452
453 info = doc._get_elem_info(elem)
454 if info is None:
455 return _no_type
456 if self.namespaceURI:
457 return info.getAttributeTypeNS(self.namespaceURI, self.localName)
458 else:
459 return info.getAttributeType(self.nodeName)
460
461defproperty(Attr, "isId", doc="True if this attribute is an ID.")
462defproperty(Attr, "localName", doc="Namespace-local name of this attribute.")
463defproperty(Attr, "schemaType", doc="Schema type for this attribute.")
Fred Drake4ccf4a12000-11-21 22:02:22 +0000464
Fred Drakef7cf40d2000-12-14 18:16:11 +0000465
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000466class NamedNodeMap(object):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000467 """The attribute list is a transient interface to the underlying
468 dictionaries. Mutations here will change the underlying element's
Fred Drakef7cf40d2000-12-14 18:16:11 +0000469 dictionary.
470
471 Ordering is imposed artificially and does not reflect the order of
472 attributes as found in an input document.
473 """
Fred Drake4ccf4a12000-11-21 22:02:22 +0000474
Martin v. Löwis787354c2003-01-25 15:28:29 +0000475 __slots__ = ('_attrs', '_attrsNS', '_ownerElement')
476
Fred Drake2998a552001-12-06 18:27:48 +0000477 def __init__(self, attrs, attrsNS, ownerElement):
Fred Drake1f549022000-09-24 05:21:58 +0000478 self._attrs = attrs
479 self._attrsNS = attrsNS
Fred Drake2998a552001-12-06 18:27:48 +0000480 self._ownerElement = ownerElement
Fred Drakef7cf40d2000-12-14 18:16:11 +0000481
Martin v. Löwis787354c2003-01-25 15:28:29 +0000482 def _get_length(self):
483 return len(self._attrs)
Fred Drake55c38192000-06-29 19:39:57 +0000484
Fred Drake1f549022000-09-24 05:21:58 +0000485 def item(self, index):
Fred Drake55c38192000-06-29 19:39:57 +0000486 try:
Brett Cannon861fd6f2007-02-21 22:05:37 +0000487 return self[list(self._attrs.keys())[index]]
Fred Drake55c38192000-06-29 19:39:57 +0000488 except IndexError:
489 return None
Fred Drake55c38192000-06-29 19:39:57 +0000490
Fred Drake1f549022000-09-24 05:21:58 +0000491 def items(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000492 L = []
493 for node in self._attrs.values():
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000494 L.append((node.nodeName, node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000495 return L
Fred Drake1f549022000-09-24 05:21:58 +0000496
497 def itemsNS(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000498 L = []
499 for node in self._attrs.values():
Fred Drake49a5d032001-11-30 22:21:58 +0000500 L.append(((node.namespaceURI, node.localName), node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000501 return L
Fred Drake16f63292000-10-23 18:09:50 +0000502
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000503 def __contains__(self, key):
Christian Heimesc9543e42007-11-28 08:28:28 +0000504 if isinstance(key, str):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000505 return key in self._attrs
Martin v. Löwis787354c2003-01-25 15:28:29 +0000506 else:
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000507 return key in self._attrsNS
Martin v. Löwis787354c2003-01-25 15:28:29 +0000508
Fred Drake1f549022000-09-24 05:21:58 +0000509 def keys(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000510 return self._attrs.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000511
Fred Drake1f549022000-09-24 05:21:58 +0000512 def keysNS(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000513 return self._attrsNS.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000514
Fred Drake1f549022000-09-24 05:21:58 +0000515 def values(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000516 return self._attrs.values()
Fred Drake55c38192000-06-29 19:39:57 +0000517
Martin v. Löwis787354c2003-01-25 15:28:29 +0000518 def get(self, name, value=None):
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000519 return self._attrs.get(name, value)
520
Martin v. Löwis787354c2003-01-25 15:28:29 +0000521 __len__ = _get_length
Fred Drake55c38192000-06-29 19:39:57 +0000522
Fred Drake1f549022000-09-24 05:21:58 +0000523 def __cmp__(self, other):
524 if self._attrs is getattr(other, "_attrs", None):
Fred Drake55c38192000-06-29 19:39:57 +0000525 return 0
Fred Drake16f63292000-10-23 18:09:50 +0000526 else:
Fred Drake1f549022000-09-24 05:21:58 +0000527 return cmp(id(self), id(other))
Fred Drake55c38192000-06-29 19:39:57 +0000528
Fred Drake1f549022000-09-24 05:21:58 +0000529 def __getitem__(self, attname_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000530 if isinstance(attname_or_tuple, tuple):
Paul Prescod73678da2000-07-01 04:58:47 +0000531 return self._attrsNS[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000532 else:
Paul Prescod73678da2000-07-01 04:58:47 +0000533 return self._attrs[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000534
Paul Prescod1e688272000-07-01 19:21:47 +0000535 # same as set
Fred Drake1f549022000-09-24 05:21:58 +0000536 def __setitem__(self, attname, value):
Christian Heimesc9543e42007-11-28 08:28:28 +0000537 if isinstance(value, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000538 try:
539 node = self._attrs[attname]
540 except KeyError:
541 node = Attr(attname)
542 node.ownerDocument = self._ownerElement.ownerDocument
Martin v. Löwis995359c2003-01-26 08:59:32 +0000543 self.setNamedItem(node)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000544 node.value = value
Paul Prescod1e688272000-07-01 19:21:47 +0000545 else:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000546 if not isinstance(value, Attr):
Collin Winter70e79802007-08-24 18:57:22 +0000547 raise TypeError("value must be a string or Attr object")
Fred Drake1f549022000-09-24 05:21:58 +0000548 node = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000549 self.setNamedItem(node)
550
551 def getNamedItem(self, name):
552 try:
553 return self._attrs[name]
554 except KeyError:
555 return None
556
557 def getNamedItemNS(self, namespaceURI, localName):
558 try:
559 return self._attrsNS[(namespaceURI, localName)]
560 except KeyError:
561 return None
562
563 def removeNamedItem(self, name):
564 n = self.getNamedItem(name)
565 if n is not None:
566 _clear_id_cache(self._ownerElement)
567 del self._attrs[n.nodeName]
568 del self._attrsNS[(n.namespaceURI, n.localName)]
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000569 if 'ownerElement' in n.__dict__:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000570 n.__dict__['ownerElement'] = None
571 return n
572 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000573 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000574
575 def removeNamedItemNS(self, namespaceURI, localName):
576 n = self.getNamedItemNS(namespaceURI, localName)
577 if n is not None:
578 _clear_id_cache(self._ownerElement)
579 del self._attrsNS[(n.namespaceURI, n.localName)]
580 del self._attrs[n.nodeName]
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000581 if 'ownerElement' in n.__dict__:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000582 n.__dict__['ownerElement'] = None
583 return n
584 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000585 raise xml.dom.NotFoundErr()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000586
587 def setNamedItem(self, node):
Andrew M. Kuchlingbc8f72c2001-02-21 01:30:26 +0000588 if not isinstance(node, Attr):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000590 "%s cannot be child of %s" % (repr(node), repr(self)))
Fred Drakef7cf40d2000-12-14 18:16:11 +0000591 old = self._attrs.get(node.name)
Paul Prescod1e688272000-07-01 19:21:47 +0000592 if old:
593 old.unlink()
Fred Drake1f549022000-09-24 05:21:58 +0000594 self._attrs[node.name] = node
595 self._attrsNS[(node.namespaceURI, node.localName)] = node
Fred Drake2998a552001-12-06 18:27:48 +0000596 node.ownerElement = self._ownerElement
Martin v. Löwis787354c2003-01-25 15:28:29 +0000597 _clear_id_cache(node.ownerElement)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000598 return old
599
600 def setNamedItemNS(self, node):
601 return self.setNamedItem(node)
Paul Prescod73678da2000-07-01 04:58:47 +0000602
Fred Drake1f549022000-09-24 05:21:58 +0000603 def __delitem__(self, attname_or_tuple):
604 node = self[attname_or_tuple]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000605 _clear_id_cache(node.ownerElement)
Paul Prescod73678da2000-07-01 04:58:47 +0000606 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000607
608 def __getstate__(self):
609 return self._attrs, self._attrsNS, self._ownerElement
610
611 def __setstate__(self, state):
612 self._attrs, self._attrsNS, self._ownerElement = state
613
614defproperty(NamedNodeMap, "length",
615 doc="Number of nodes in the NamedNodeMap.")
Fred Drakef7cf40d2000-12-14 18:16:11 +0000616
617AttributeList = NamedNodeMap
618
Fred Drake1f549022000-09-24 05:21:58 +0000619
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000620class TypeInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000621 __slots__ = 'namespace', 'name'
622
623 def __init__(self, namespace, name):
624 self.namespace = namespace
625 self.name = name
626
627 def __repr__(self):
628 if self.namespace:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000629 return "<TypeInfo %r (from %r)>" % (self.name, self.namespace)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000630 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000631 return "<TypeInfo %r>" % self.name
Martin v. Löwis787354c2003-01-25 15:28:29 +0000632
633 def _get_name(self):
634 return self.name
635
636 def _get_namespace(self):
637 return self.namespace
638
639_no_type = TypeInfo(None, None)
640
Martin v. Löwisa2fda0d2000-10-07 12:10:28 +0000641class Element(Node):
Fred Drake1f549022000-09-24 05:21:58 +0000642 nodeType = Node.ELEMENT_NODE
Martin v. Löwis787354c2003-01-25 15:28:29 +0000643 nodeValue = None
644 schemaType = _no_type
645
646 _magic_id_nodes = 0
647
648 _child_node_types = (Node.ELEMENT_NODE,
649 Node.PROCESSING_INSTRUCTION_NODE,
650 Node.COMMENT_NODE,
651 Node.TEXT_NODE,
652 Node.CDATA_SECTION_NODE,
653 Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000654
Fred Drake49a5d032001-11-30 22:21:58 +0000655 def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None,
Fred Drake1f549022000-09-24 05:21:58 +0000656 localName=None):
Fred Drake55c38192000-06-29 19:39:57 +0000657 self.tagName = self.nodeName = tagName
Fred Drake1f549022000-09-24 05:21:58 +0000658 self.prefix = prefix
659 self.namespaceURI = namespaceURI
Martin v. Löwis787354c2003-01-25 15:28:29 +0000660 self.childNodes = NodeList()
Fred Drake55c38192000-06-29 19:39:57 +0000661
Fred Drake4ccf4a12000-11-21 22:02:22 +0000662 self._attrs = {} # attributes are double-indexed:
663 self._attrsNS = {} # tagName -> Attribute
664 # URI,localName -> Attribute
665 # in the future: consider lazy generation
666 # of attribute objects this is too tricky
667 # for now because of headaches with
668 # namespaces.
669
Martin v. Löwis787354c2003-01-25 15:28:29 +0000670 def _get_localName(self):
Alex Martelli0ee43512006-08-21 19:53:20 +0000671 if 'localName' in self.__dict__:
Guido van Rossum3e1f85e2007-07-27 18:03:11 +0000672 return self.__dict__['localName']
Martin v. Löwis787354c2003-01-25 15:28:29 +0000673 return self.tagName.split(":", 1)[-1]
674
675 def _get_tagName(self):
676 return self.tagName
Fred Drake4ccf4a12000-11-21 22:02:22 +0000677
678 def unlink(self):
Brett Cannon861fd6f2007-02-21 22:05:37 +0000679 for attr in list(self._attrs.values()):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000680 attr.unlink()
681 self._attrs = None
682 self._attrsNS = None
683 Node.unlink(self)
Fred Drake55c38192000-06-29 19:39:57 +0000684
Fred Drake1f549022000-09-24 05:21:58 +0000685 def getAttribute(self, attname):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000686 try:
687 return self._attrs[attname].value
688 except KeyError:
689 return ""
Fred Drake55c38192000-06-29 19:39:57 +0000690
Fred Drake1f549022000-09-24 05:21:58 +0000691 def getAttributeNS(self, namespaceURI, localName):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000692 try:
693 return self._attrsNS[(namespaceURI, localName)].value
694 except KeyError:
695 return ""
Fred Drake1f549022000-09-24 05:21:58 +0000696
697 def setAttribute(self, attname, value):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000698 attr = self.getAttributeNode(attname)
699 if attr is None:
700 attr = Attr(attname)
701 # for performance
702 d = attr.__dict__
703 d["value"] = d["nodeValue"] = value
704 d["ownerDocument"] = self.ownerDocument
705 self.setAttributeNode(attr)
706 elif value != attr.value:
707 d = attr.__dict__
708 d["value"] = d["nodeValue"] = value
709 if attr.isId:
710 _clear_id_cache(self)
Fred Drake55c38192000-06-29 19:39:57 +0000711
Fred Drake1f549022000-09-24 05:21:58 +0000712 def setAttributeNS(self, namespaceURI, qualifiedName, value):
713 prefix, localname = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000714 attr = self.getAttributeNodeNS(namespaceURI, localname)
715 if attr is None:
716 # for performance
717 attr = Attr(qualifiedName, namespaceURI, localname, prefix)
718 d = attr.__dict__
719 d["prefix"] = prefix
720 d["nodeName"] = qualifiedName
721 d["value"] = d["nodeValue"] = value
722 d["ownerDocument"] = self.ownerDocument
723 self.setAttributeNode(attr)
724 else:
725 d = attr.__dict__
726 if value != attr.value:
727 d["value"] = d["nodeValue"] = value
728 if attr.isId:
729 _clear_id_cache(self)
730 if attr.prefix != prefix:
731 d["prefix"] = prefix
732 d["nodeName"] = qualifiedName
Fred Drake55c38192000-06-29 19:39:57 +0000733
Fred Drake1f549022000-09-24 05:21:58 +0000734 def getAttributeNode(self, attrname):
735 return self._attrs.get(attrname)
Paul Prescod73678da2000-07-01 04:58:47 +0000736
Fred Drake1f549022000-09-24 05:21:58 +0000737 def getAttributeNodeNS(self, namespaceURI, localName):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000738 return self._attrsNS.get((namespaceURI, localName))
Paul Prescod73678da2000-07-01 04:58:47 +0000739
Fred Drake1f549022000-09-24 05:21:58 +0000740 def setAttributeNode(self, attr):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000741 if attr.ownerElement not in (None, self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000742 raise xml.dom.InuseAttributeErr("attribute node already owned")
Martin v. Löwis787354c2003-01-25 15:28:29 +0000743 old1 = self._attrs.get(attr.name, None)
744 if old1 is not None:
745 self.removeAttributeNode(old1)
746 old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None)
747 if old2 is not None and old2 is not old1:
748 self.removeAttributeNode(old2)
749 _set_attribute_node(self, attr)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000750
Martin v. Löwis787354c2003-01-25 15:28:29 +0000751 if old1 is not attr:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000752 # It might have already been part of this node, in which case
753 # it doesn't represent a change, and should not be returned.
Martin v. Löwis787354c2003-01-25 15:28:29 +0000754 return old1
755 if old2 is not attr:
756 return old2
Fred Drake55c38192000-06-29 19:39:57 +0000757
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000758 setAttributeNodeNS = setAttributeNode
759
Fred Drake1f549022000-09-24 05:21:58 +0000760 def removeAttribute(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000761 try:
762 attr = self._attrs[name]
763 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000764 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000765 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000766
Fred Drake1f549022000-09-24 05:21:58 +0000767 def removeAttributeNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000768 try:
769 attr = self._attrsNS[(namespaceURI, localName)]
770 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000771 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000772 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000773
Fred Drake1f549022000-09-24 05:21:58 +0000774 def removeAttributeNode(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000775 if node is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000776 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000777 try:
778 self._attrs[node.name]
779 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000780 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000781 _clear_id_cache(self)
Paul Prescod73678da2000-07-01 04:58:47 +0000782 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000783 # Restore this since the node is still useful and otherwise
784 # unlinked
785 node.ownerDocument = self.ownerDocument
Fred Drake16f63292000-10-23 18:09:50 +0000786
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000787 removeAttributeNodeNS = removeAttributeNode
788
Martin v. Löwis156c3372000-12-28 18:40:56 +0000789 def hasAttribute(self, name):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000790 return name in self._attrs
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000791
Martin v. Löwis156c3372000-12-28 18:40:56 +0000792 def hasAttributeNS(self, namespaceURI, localName):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000793 return (namespaceURI, localName) in self._attrsNS
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000794
Fred Drake1f549022000-09-24 05:21:58 +0000795 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000796 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000797
Fred Drake1f549022000-09-24 05:21:58 +0000798 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000799 return _get_elements_by_tagName_ns_helper(
800 self, namespaceURI, localName, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000801
Fred Drake1f549022000-09-24 05:21:58 +0000802 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000803 return "<DOM Element: %s at %#x>" % (self.tagName, id(self))
Fred Drake55c38192000-06-29 19:39:57 +0000804
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000805 def writexml(self, writer, indent="", addindent="", newl=""):
806 # indent = current indentation
807 # addindent = indentation to add to higher levels
808 # newl = newline string
809 writer.write(indent+"<" + self.tagName)
Fred Drake16f63292000-10-23 18:09:50 +0000810
Fred Drake4ccf4a12000-11-21 22:02:22 +0000811 attrs = self._get_attributes()
Brett Cannon861fd6f2007-02-21 22:05:37 +0000812 a_names = sorted(attrs.keys())
Fred Drake55c38192000-06-29 19:39:57 +0000813
814 for a_name in a_names:
Fred Drake1f549022000-09-24 05:21:58 +0000815 writer.write(" %s=\"" % a_name)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000816 _write_data(writer, attrs[a_name].value)
Fred Drake55c38192000-06-29 19:39:57 +0000817 writer.write("\"")
818 if self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000819 writer.write(">%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000820 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000821 node.writexml(writer,indent+addindent,addindent,newl)
822 writer.write("%s</%s>%s" % (indent,self.tagName,newl))
Fred Drake55c38192000-06-29 19:39:57 +0000823 else:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000824 writer.write("/>%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000825
Fred Drake1f549022000-09-24 05:21:58 +0000826 def _get_attributes(self):
Fred Drake2998a552001-12-06 18:27:48 +0000827 return NamedNodeMap(self._attrs, self._attrsNS, self)
Fred Drake55c38192000-06-29 19:39:57 +0000828
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000829 def hasAttributes(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000830 if self._attrs:
831 return True
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000832 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000833 return False
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000834
Martin v. Löwis787354c2003-01-25 15:28:29 +0000835 # DOM Level 3 attributes, based on the 22 Oct 2002 draft
836
837 def setIdAttribute(self, name):
838 idAttr = self.getAttributeNode(name)
839 self.setIdAttributeNode(idAttr)
840
841 def setIdAttributeNS(self, namespaceURI, localName):
842 idAttr = self.getAttributeNodeNS(namespaceURI, localName)
843 self.setIdAttributeNode(idAttr)
844
845 def setIdAttributeNode(self, idAttr):
846 if idAttr is None or not self.isSameNode(idAttr.ownerElement):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000847 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000848 if _get_containing_entref(self) is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000849 raise xml.dom.NoModificationAllowedErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000850 if not idAttr._is_id:
851 idAttr.__dict__['_is_id'] = True
852 self._magic_id_nodes += 1
853 self.ownerDocument._magic_id_count += 1
854 _clear_id_cache(self)
855
856defproperty(Element, "attributes",
857 doc="NamedNodeMap of attributes on the element.")
858defproperty(Element, "localName",
859 doc="Namespace-local name of this element.")
860
861
862def _set_attribute_node(element, attr):
863 _clear_id_cache(element)
864 element._attrs[attr.name] = attr
865 element._attrsNS[(attr.namespaceURI, attr.localName)] = attr
866
867 # This creates a circular reference, but Element.unlink()
868 # breaks the cycle since the references to the attribute
869 # dictionaries are tossed.
870 attr.__dict__['ownerElement'] = element
871
872
873class Childless:
874 """Mixin that makes childless-ness easy to implement and avoids
875 the complexity of the Node methods that deal with children.
876 """
877
Fred Drake4ccf4a12000-11-21 22:02:22 +0000878 attributes = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000879 childNodes = EmptyNodeList()
880 firstChild = None
881 lastChild = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000882
Martin v. Löwis787354c2003-01-25 15:28:29 +0000883 def _get_firstChild(self):
884 return None
Fred Drake55c38192000-06-29 19:39:57 +0000885
Martin v. Löwis787354c2003-01-25 15:28:29 +0000886 def _get_lastChild(self):
887 return None
Fred Drake1f549022000-09-24 05:21:58 +0000888
Martin v. Löwis787354c2003-01-25 15:28:29 +0000889 def appendChild(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000890 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000891 self.nodeName + " nodes cannot have children")
892
893 def hasChildNodes(self):
894 return False
895
896 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000897 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000898 self.nodeName + " nodes do not have children")
899
900 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000901 raise xml.dom.NotFoundErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000902 self.nodeName + " nodes do not have children")
903
904 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000905 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000906 self.nodeName + " nodes do not have children")
907
908
909class ProcessingInstruction(Childless, Node):
Fred Drake1f549022000-09-24 05:21:58 +0000910 nodeType = Node.PROCESSING_INSTRUCTION_NODE
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000911
Fred Drake1f549022000-09-24 05:21:58 +0000912 def __init__(self, target, data):
Fred Drake55c38192000-06-29 19:39:57 +0000913 self.target = self.nodeName = target
914 self.data = self.nodeValue = data
Fred Drake55c38192000-06-29 19:39:57 +0000915
Martin v. Löwis787354c2003-01-25 15:28:29 +0000916 def _get_data(self):
917 return self.data
918 def _set_data(self, value):
919 d = self.__dict__
920 d['data'] = d['nodeValue'] = value
921
922 def _get_target(self):
923 return self.target
924 def _set_target(self, value):
925 d = self.__dict__
926 d['target'] = d['nodeName'] = value
927
928 def __setattr__(self, name, value):
929 if name == "data" or name == "nodeValue":
930 self.__dict__['data'] = self.__dict__['nodeValue'] = value
931 elif name == "target" or name == "nodeName":
932 self.__dict__['target'] = self.__dict__['nodeName'] = value
933 else:
934 self.__dict__[name] = value
935
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000936 def writexml(self, writer, indent="", addindent="", newl=""):
937 writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000938
Martin v. Löwis787354c2003-01-25 15:28:29 +0000939
940class CharacterData(Childless, Node):
941 def _get_length(self):
942 return len(self.data)
943 __len__ = _get_length
944
945 def _get_data(self):
946 return self.__dict__['data']
947 def _set_data(self, data):
948 d = self.__dict__
949 d['data'] = d['nodeValue'] = data
950
951 _get_nodeValue = _get_data
952 _set_nodeValue = _set_data
953
954 def __setattr__(self, name, value):
955 if name == "data" or name == "nodeValue":
956 self.__dict__['data'] = self.__dict__['nodeValue'] = value
957 else:
958 self.__dict__[name] = value
Fred Drake87432f42001-04-04 14:09:46 +0000959
Fred Drake55c38192000-06-29 19:39:57 +0000960 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000961 data = self.data
962 if len(data) > 10:
Fred Drake1f549022000-09-24 05:21:58 +0000963 dotdotdot = "..."
Fred Drake55c38192000-06-29 19:39:57 +0000964 else:
Fred Drake1f549022000-09-24 05:21:58 +0000965 dotdotdot = ""
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000966 return '<DOM %s node "%r%s">' % (
Martin v. Löwis787354c2003-01-25 15:28:29 +0000967 self.__class__.__name__, data[0:10], dotdotdot)
Fred Drake87432f42001-04-04 14:09:46 +0000968
969 def substringData(self, offset, count):
970 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000971 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000972 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000973 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +0000974 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000975 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000976 return self.data[offset:offset+count]
977
978 def appendData(self, arg):
979 self.data = self.data + arg
Fred Drake87432f42001-04-04 14:09:46 +0000980
981 def insertData(self, offset, arg):
982 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000983 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000984 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000985 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +0000986 if arg:
987 self.data = "%s%s%s" % (
988 self.data[:offset], arg, self.data[offset:])
Fred Drake87432f42001-04-04 14:09:46 +0000989
990 def deleteData(self, offset, count):
991 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000992 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000993 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000994 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +0000995 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000996 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000997 if count:
998 self.data = self.data[:offset] + self.data[offset+count:]
Fred Drake87432f42001-04-04 14:09:46 +0000999
1000 def replaceData(self, offset, count, arg):
1001 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001002 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001003 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001004 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001005 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001006 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001007 if count:
1008 self.data = "%s%s%s" % (
1009 self.data[:offset], arg, self.data[offset+count:])
Martin v. Löwis787354c2003-01-25 15:28:29 +00001010
1011defproperty(CharacterData, "length", doc="Length of the string data.")
1012
Fred Drake87432f42001-04-04 14:09:46 +00001013
1014class Text(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001015 # Make sure we don't add an instance __dict__ if we don't already
1016 # have one, at least when that's possible:
Martin v. Löwis995359c2003-01-26 08:59:32 +00001017 # XXX this does not work, CharacterData is an old-style class
1018 # __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001019
Fred Drake87432f42001-04-04 14:09:46 +00001020 nodeType = Node.TEXT_NODE
1021 nodeName = "#text"
1022 attributes = None
Fred Drake55c38192000-06-29 19:39:57 +00001023
Fred Drakef7cf40d2000-12-14 18:16:11 +00001024 def splitText(self, offset):
1025 if offset < 0 or offset > len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001026 raise xml.dom.IndexSizeErr("illegal offset value")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001027 newText = self.__class__()
1028 newText.data = self.data[offset:]
1029 newText.ownerDocument = self.ownerDocument
Fred Drakef7cf40d2000-12-14 18:16:11 +00001030 next = self.nextSibling
1031 if self.parentNode and self in self.parentNode.childNodes:
1032 if next is None:
1033 self.parentNode.appendChild(newText)
1034 else:
1035 self.parentNode.insertBefore(newText, next)
1036 self.data = self.data[:offset]
1037 return newText
1038
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001039 def writexml(self, writer, indent="", addindent="", newl=""):
1040 _write_data(writer, "%s%s%s"%(indent, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001041
Martin v. Löwis787354c2003-01-25 15:28:29 +00001042 # DOM Level 3 (WD 9 April 2002)
1043
1044 def _get_wholeText(self):
1045 L = [self.data]
1046 n = self.previousSibling
1047 while n is not None:
1048 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1049 L.insert(0, n.data)
1050 n = n.previousSibling
1051 else:
1052 break
1053 n = self.nextSibling
1054 while n is not None:
1055 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1056 L.append(n.data)
1057 n = n.nextSibling
1058 else:
1059 break
1060 return ''.join(L)
1061
1062 def replaceWholeText(self, content):
1063 # XXX This needs to be seriously changed if minidom ever
1064 # supports EntityReference nodes.
1065 parent = self.parentNode
1066 n = self.previousSibling
1067 while n is not None:
1068 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1069 next = n.previousSibling
1070 parent.removeChild(n)
1071 n = next
1072 else:
1073 break
1074 n = self.nextSibling
1075 if not content:
1076 parent.removeChild(self)
1077 while n is not None:
1078 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1079 next = n.nextSibling
1080 parent.removeChild(n)
1081 n = next
1082 else:
1083 break
1084 if content:
1085 d = self.__dict__
1086 d['data'] = content
1087 d['nodeValue'] = content
1088 return self
1089 else:
1090 return None
1091
1092 def _get_isWhitespaceInElementContent(self):
1093 if self.data.strip():
1094 return False
1095 elem = _get_containing_element(self)
1096 if elem is None:
1097 return False
1098 info = self.ownerDocument._get_elem_info(elem)
1099 if info is None:
1100 return False
1101 else:
1102 return info.isElementContent()
1103
1104defproperty(Text, "isWhitespaceInElementContent",
1105 doc="True iff this text node contains only whitespace"
1106 " and is in element content.")
1107defproperty(Text, "wholeText",
1108 doc="The text of all logically-adjacent text nodes.")
1109
1110
1111def _get_containing_element(node):
1112 c = node.parentNode
1113 while c is not None:
1114 if c.nodeType == Node.ELEMENT_NODE:
1115 return c
1116 c = c.parentNode
1117 return None
1118
1119def _get_containing_entref(node):
1120 c = node.parentNode
1121 while c is not None:
1122 if c.nodeType == Node.ENTITY_REFERENCE_NODE:
1123 return c
1124 c = c.parentNode
1125 return None
1126
1127
Alex Martelli0ee43512006-08-21 19:53:20 +00001128class Comment(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001129 nodeType = Node.COMMENT_NODE
1130 nodeName = "#comment"
1131
1132 def __init__(self, data):
1133 self.data = self.nodeValue = data
1134
1135 def writexml(self, writer, indent="", addindent="", newl=""):
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001136 if "--" in self.data:
1137 raise ValueError("'--' is not allowed in a comment node")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001138 writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1139
Fred Drake87432f42001-04-04 14:09:46 +00001140
1141class CDATASection(Text):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001142 # Make sure we don't add an instance __dict__ if we don't already
1143 # have one, at least when that's possible:
Martin v. Löwis995359c2003-01-26 08:59:32 +00001144 # XXX this does not work, Text is an old-style class
1145 # __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001146
Fred Drake87432f42001-04-04 14:09:46 +00001147 nodeType = Node.CDATA_SECTION_NODE
1148 nodeName = "#cdata-section"
1149
1150 def writexml(self, writer, indent="", addindent="", newl=""):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001151 if self.data.find("]]>") >= 0:
1152 raise ValueError("']]>' not allowed in a CDATA section")
Guido van Rossum5b5e0b92001-09-19 13:28:25 +00001153 writer.write("<![CDATA[%s]]>" % self.data)
Fred Drake87432f42001-04-04 14:09:46 +00001154
1155
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001156class ReadOnlySequentialNamedNodeMap(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001157 __slots__ = '_seq',
1158
1159 def __init__(self, seq=()):
1160 # seq should be a list or tuple
1161 self._seq = seq
1162
1163 def __len__(self):
1164 return len(self._seq)
1165
1166 def _get_length(self):
1167 return len(self._seq)
1168
1169 def getNamedItem(self, name):
1170 for n in self._seq:
1171 if n.nodeName == name:
1172 return n
1173
1174 def getNamedItemNS(self, namespaceURI, localName):
1175 for n in self._seq:
1176 if n.namespaceURI == namespaceURI and n.localName == localName:
1177 return n
1178
1179 def __getitem__(self, name_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001180 if isinstance(name_or_tuple, tuple):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001181 node = self.getNamedItemNS(*name_or_tuple)
1182 else:
1183 node = self.getNamedItem(name_or_tuple)
1184 if node is None:
Collin Winter70e79802007-08-24 18:57:22 +00001185 raise KeyError(name_or_tuple)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001186 return node
1187
1188 def item(self, index):
1189 if index < 0:
1190 return None
1191 try:
1192 return self._seq[index]
1193 except IndexError:
1194 return None
1195
1196 def removeNamedItem(self, name):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001197 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001198 "NamedNodeMap instance is read-only")
1199
1200 def removeNamedItemNS(self, namespaceURI, localName):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001201 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001202 "NamedNodeMap instance is read-only")
1203
1204 def setNamedItem(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001205 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001206 "NamedNodeMap instance is read-only")
1207
1208 def setNamedItemNS(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001209 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001210 "NamedNodeMap instance is read-only")
1211
1212 def __getstate__(self):
1213 return [self._seq]
1214
1215 def __setstate__(self, state):
1216 self._seq = state[0]
1217
1218defproperty(ReadOnlySequentialNamedNodeMap, "length",
1219 doc="Number of entries in the NamedNodeMap.")
Paul Prescod73678da2000-07-01 04:58:47 +00001220
Fred Drakef7cf40d2000-12-14 18:16:11 +00001221
Martin v. Löwis787354c2003-01-25 15:28:29 +00001222class Identified:
1223 """Mix-in class that supports the publicId and systemId attributes."""
1224
Martin v. Löwis995359c2003-01-26 08:59:32 +00001225 # XXX this does not work, this is an old-style class
1226 # __slots__ = 'publicId', 'systemId'
Martin v. Löwis787354c2003-01-25 15:28:29 +00001227
1228 def _identified_mixin_init(self, publicId, systemId):
1229 self.publicId = publicId
1230 self.systemId = systemId
1231
1232 def _get_publicId(self):
1233 return self.publicId
1234
1235 def _get_systemId(self):
1236 return self.systemId
1237
1238class DocumentType(Identified, Childless, Node):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001239 nodeType = Node.DOCUMENT_TYPE_NODE
1240 nodeValue = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001241 name = None
1242 publicId = None
1243 systemId = None
Fred Drakedc806702001-04-05 14:41:30 +00001244 internalSubset = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001245
1246 def __init__(self, qualifiedName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001247 self.entities = ReadOnlySequentialNamedNodeMap()
1248 self.notations = ReadOnlySequentialNamedNodeMap()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001249 if qualifiedName:
1250 prefix, localname = _nssplit(qualifiedName)
1251 self.name = localname
Martin v. Löwis787354c2003-01-25 15:28:29 +00001252 self.nodeName = self.name
1253
1254 def _get_internalSubset(self):
1255 return self.internalSubset
1256
1257 def cloneNode(self, deep):
1258 if self.ownerDocument is None:
1259 # it's ok
1260 clone = DocumentType(None)
1261 clone.name = self.name
1262 clone.nodeName = self.name
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001263 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001264 if deep:
1265 clone.entities._seq = []
1266 clone.notations._seq = []
1267 for n in self.notations._seq:
1268 notation = Notation(n.nodeName, n.publicId, n.systemId)
1269 clone.notations._seq.append(notation)
1270 n._call_user_data_handler(operation, n, notation)
1271 for e in self.entities._seq:
1272 entity = Entity(e.nodeName, e.publicId, e.systemId,
1273 e.notationName)
1274 entity.actualEncoding = e.actualEncoding
1275 entity.encoding = e.encoding
1276 entity.version = e.version
1277 clone.entities._seq.append(entity)
1278 e._call_user_data_handler(operation, n, entity)
1279 self._call_user_data_handler(operation, self, clone)
1280 return clone
1281 else:
1282 return None
1283
1284 def writexml(self, writer, indent="", addindent="", newl=""):
1285 writer.write("<!DOCTYPE ")
1286 writer.write(self.name)
1287 if self.publicId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001288 writer.write("%s PUBLIC '%s'%s '%s'"
1289 % (newl, self.publicId, newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001290 elif self.systemId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001291 writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001292 if self.internalSubset is not None:
1293 writer.write(" [")
1294 writer.write(self.internalSubset)
1295 writer.write("]")
Georg Brandl175a7dc2005-08-25 22:02:43 +00001296 writer.write(">"+newl)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001297
1298class Entity(Identified, Node):
1299 attributes = None
1300 nodeType = Node.ENTITY_NODE
1301 nodeValue = None
1302
1303 actualEncoding = None
1304 encoding = None
1305 version = None
1306
1307 def __init__(self, name, publicId, systemId, notation):
1308 self.nodeName = name
1309 self.notationName = notation
1310 self.childNodes = NodeList()
1311 self._identified_mixin_init(publicId, systemId)
1312
1313 def _get_actualEncoding(self):
1314 return self.actualEncoding
1315
1316 def _get_encoding(self):
1317 return self.encoding
1318
1319 def _get_version(self):
1320 return self.version
1321
1322 def appendChild(self, newChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001323 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001324 "cannot append children to an entity node")
1325
1326 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001327 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001328 "cannot insert children below an entity node")
1329
1330 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001331 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001332 "cannot remove children from an entity node")
1333
1334 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001335 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001336 "cannot replace children of an entity node")
1337
1338class Notation(Identified, Childless, Node):
1339 nodeType = Node.NOTATION_NODE
1340 nodeValue = None
1341
1342 def __init__(self, name, publicId, systemId):
1343 self.nodeName = name
1344 self._identified_mixin_init(publicId, systemId)
Fred Drakef7cf40d2000-12-14 18:16:11 +00001345
1346
Martin v. Löwis787354c2003-01-25 15:28:29 +00001347class DOMImplementation(DOMImplementationLS):
1348 _features = [("core", "1.0"),
1349 ("core", "2.0"),
1350 ("core", "3.0"),
1351 ("core", None),
1352 ("xml", "1.0"),
1353 ("xml", "2.0"),
1354 ("xml", "3.0"),
1355 ("xml", None),
1356 ("ls-load", "3.0"),
1357 ("ls-load", None),
1358 ]
1359
Fred Drakef7cf40d2000-12-14 18:16:11 +00001360 def hasFeature(self, feature, version):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001361 if version == "":
1362 version = None
1363 return (feature.lower(), version) in self._features
Fred Drakef7cf40d2000-12-14 18:16:11 +00001364
1365 def createDocument(self, namespaceURI, qualifiedName, doctype):
1366 if doctype and doctype.parentNode is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001367 raise xml.dom.WrongDocumentErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001368 "doctype object owned by another DOM tree")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001369 doc = self._create_document()
1370
1371 add_root_element = not (namespaceURI is None
1372 and qualifiedName is None
1373 and doctype is None)
1374
1375 if not qualifiedName and add_root_element:
Martin v. Löwisb417be22001-02-06 01:16:06 +00001376 # The spec is unclear what to raise here; SyntaxErr
1377 # would be the other obvious candidate. Since Xerces raises
1378 # InvalidCharacterErr, and since SyntaxErr is not listed
1379 # for createDocument, that seems to be the better choice.
1380 # XXX: need to check for illegal characters here and in
1381 # createElement.
Martin v. Löwis787354c2003-01-25 15:28:29 +00001382
1383 # DOM Level III clears this up when talking about the return value
1384 # of this function. If namespaceURI, qName and DocType are
1385 # Null the document is returned without a document element
1386 # Otherwise if doctype or namespaceURI are not None
1387 # Then we go back to the above problem
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001388 raise xml.dom.InvalidCharacterErr("Element with no name")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001389
1390 if add_root_element:
1391 prefix, localname = _nssplit(qualifiedName)
1392 if prefix == "xml" \
1393 and namespaceURI != "http://www.w3.org/XML/1998/namespace":
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001394 raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001395 if prefix and not namespaceURI:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001396 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001397 "illegal use of prefix without namespaces")
1398 element = doc.createElementNS(namespaceURI, qualifiedName)
1399 if doctype:
1400 doc.appendChild(doctype)
1401 doc.appendChild(element)
1402
1403 if doctype:
1404 doctype.parentNode = doctype.ownerDocument = doc
1405
Fred Drakef7cf40d2000-12-14 18:16:11 +00001406 doc.doctype = doctype
1407 doc.implementation = self
1408 return doc
1409
1410 def createDocumentType(self, qualifiedName, publicId, systemId):
1411 doctype = DocumentType(qualifiedName)
1412 doctype.publicId = publicId
1413 doctype.systemId = systemId
1414 return doctype
1415
Martin v. Löwis787354c2003-01-25 15:28:29 +00001416 # DOM Level 3 (WD 9 April 2002)
1417
1418 def getInterface(self, feature):
1419 if self.hasFeature(feature, None):
1420 return self
1421 else:
1422 return None
1423
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001424 # internal
Martin v. Löwis787354c2003-01-25 15:28:29 +00001425 def _create_document(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001426 return Document()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001427
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001428class ElementInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001429 """Object that represents content-model information for an element.
1430
1431 This implementation is not expected to be used in practice; DOM
1432 builders should provide implementations which do the right thing
1433 using information available to it.
1434
1435 """
1436
1437 __slots__ = 'tagName',
1438
1439 def __init__(self, name):
1440 self.tagName = name
1441
1442 def getAttributeType(self, aname):
1443 return _no_type
1444
1445 def getAttributeTypeNS(self, namespaceURI, localName):
1446 return _no_type
1447
1448 def isElementContent(self):
1449 return False
1450
1451 def isEmpty(self):
1452 """Returns true iff this element is declared to have an EMPTY
1453 content model."""
1454 return False
1455
1456 def isId(self, aname):
1457 """Returns true iff the named attribte is a DTD-style ID."""
1458 return False
1459
1460 def isIdNS(self, namespaceURI, localName):
1461 """Returns true iff the identified attribute is a DTD-style ID."""
1462 return False
1463
1464 def __getstate__(self):
1465 return self.tagName
1466
1467 def __setstate__(self, state):
1468 self.tagName = state
1469
1470def _clear_id_cache(node):
1471 if node.nodeType == Node.DOCUMENT_NODE:
1472 node._id_cache.clear()
1473 node._id_search_stack = None
1474 elif _in_document(node):
1475 node.ownerDocument._id_cache.clear()
1476 node.ownerDocument._id_search_stack= None
1477
1478class Document(Node, DocumentLS):
1479 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
1480 Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE)
1481
Fred Drake1f549022000-09-24 05:21:58 +00001482 nodeType = Node.DOCUMENT_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +00001483 nodeName = "#document"
1484 nodeValue = None
1485 attributes = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001486 doctype = None
1487 parentNode = None
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001488 previousSibling = nextSibling = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001489
1490 implementation = DOMImplementation()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001491
1492 # Document attributes from Level 3 (WD 9 April 2002)
1493
1494 actualEncoding = None
1495 encoding = None
1496 standalone = None
1497 version = None
1498 strictErrorChecking = False
1499 errorHandler = None
1500 documentURI = None
1501
1502 _magic_id_count = 0
1503
1504 def __init__(self):
1505 self.childNodes = NodeList()
1506 # mapping of (namespaceURI, localName) -> ElementInfo
1507 # and tagName -> ElementInfo
1508 self._elem_info = {}
1509 self._id_cache = {}
1510 self._id_search_stack = None
1511
1512 def _get_elem_info(self, element):
1513 if element.namespaceURI:
1514 key = element.namespaceURI, element.localName
1515 else:
1516 key = element.tagName
1517 return self._elem_info.get(key)
1518
1519 def _get_actualEncoding(self):
1520 return self.actualEncoding
1521
1522 def _get_doctype(self):
1523 return self.doctype
1524
1525 def _get_documentURI(self):
1526 return self.documentURI
1527
1528 def _get_encoding(self):
1529 return self.encoding
1530
1531 def _get_errorHandler(self):
1532 return self.errorHandler
1533
1534 def _get_standalone(self):
1535 return self.standalone
1536
1537 def _get_strictErrorChecking(self):
1538 return self.strictErrorChecking
1539
1540 def _get_version(self):
1541 return self.version
Fred Drake55c38192000-06-29 19:39:57 +00001542
Fred Drake1f549022000-09-24 05:21:58 +00001543 def appendChild(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001544 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001545 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001546 "%s cannot be child of %s" % (repr(node), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001547 if node.parentNode is not None:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001548 # This needs to be done before the next test since this
1549 # may *be* the document element, in which case it should
1550 # end up re-ordered to the end.
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001551 node.parentNode.removeChild(node)
1552
Fred Drakef7cf40d2000-12-14 18:16:11 +00001553 if node.nodeType == Node.ELEMENT_NODE \
1554 and self._get_documentElement():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001555 raise xml.dom.HierarchyRequestErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001556 "two document elements disallowed")
Fred Drake4ccf4a12000-11-21 22:02:22 +00001557 return Node.appendChild(self, node)
Paul Prescod73678da2000-07-01 04:58:47 +00001558
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001559 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001560 try:
1561 self.childNodes.remove(oldChild)
1562 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001563 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001564 oldChild.nextSibling = oldChild.previousSibling = None
1565 oldChild.parentNode = None
1566 if self.documentElement is oldChild:
1567 self.documentElement = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +00001568
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001569 return oldChild
1570
Fred Drakef7cf40d2000-12-14 18:16:11 +00001571 def _get_documentElement(self):
1572 for node in self.childNodes:
1573 if node.nodeType == Node.ELEMENT_NODE:
1574 return node
1575
1576 def unlink(self):
1577 if self.doctype is not None:
1578 self.doctype.unlink()
1579 self.doctype = None
1580 Node.unlink(self)
1581
Martin v. Löwis787354c2003-01-25 15:28:29 +00001582 def cloneNode(self, deep):
1583 if not deep:
1584 return None
1585 clone = self.implementation.createDocument(None, None, None)
1586 clone.encoding = self.encoding
1587 clone.standalone = self.standalone
1588 clone.version = self.version
1589 for n in self.childNodes:
1590 childclone = _clone_node(n, deep, clone)
1591 assert childclone.ownerDocument.isSameNode(clone)
1592 clone.childNodes.append(childclone)
1593 if childclone.nodeType == Node.DOCUMENT_NODE:
1594 assert clone.documentElement is None
1595 elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE:
1596 assert clone.doctype is None
1597 clone.doctype = childclone
1598 childclone.parentNode = clone
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001599 self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED,
Martin v. Löwis787354c2003-01-25 15:28:29 +00001600 self, clone)
1601 return clone
1602
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001603 def createDocumentFragment(self):
1604 d = DocumentFragment()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001605 d.ownerDocument = self
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001606 return d
Fred Drake55c38192000-06-29 19:39:57 +00001607
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001608 def createElement(self, tagName):
1609 e = Element(tagName)
1610 e.ownerDocument = self
1611 return e
Fred Drake55c38192000-06-29 19:39:57 +00001612
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001613 def createTextNode(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001614 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001615 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001616 t = Text()
1617 t.data = data
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001618 t.ownerDocument = self
1619 return t
Fred Drake55c38192000-06-29 19:39:57 +00001620
Fred Drake87432f42001-04-04 14:09:46 +00001621 def createCDATASection(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001622 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001623 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001624 c = CDATASection()
1625 c.data = data
Fred Drake87432f42001-04-04 14:09:46 +00001626 c.ownerDocument = self
1627 return c
1628
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001629 def createComment(self, data):
1630 c = Comment(data)
1631 c.ownerDocument = self
1632 return c
Fred Drake55c38192000-06-29 19:39:57 +00001633
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001634 def createProcessingInstruction(self, target, data):
1635 p = ProcessingInstruction(target, data)
1636 p.ownerDocument = self
1637 return p
1638
1639 def createAttribute(self, qName):
1640 a = Attr(qName)
1641 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001642 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001643 return a
Fred Drake55c38192000-06-29 19:39:57 +00001644
1645 def createElementNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001646 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001647 e = Element(qualifiedName, namespaceURI, prefix)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001648 e.ownerDocument = self
1649 return e
Fred Drake55c38192000-06-29 19:39:57 +00001650
1651 def createAttributeNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001652 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001653 a = Attr(qualifiedName, namespaceURI, localName, prefix)
1654 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001655 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001656 return a
Fred Drake55c38192000-06-29 19:39:57 +00001657
Martin v. Löwis787354c2003-01-25 15:28:29 +00001658 # A couple of implementation-specific helpers to create node types
1659 # not supported by the W3C DOM specs:
1660
1661 def _create_entity(self, name, publicId, systemId, notationName):
1662 e = Entity(name, publicId, systemId, notationName)
1663 e.ownerDocument = self
1664 return e
1665
1666 def _create_notation(self, name, publicId, systemId):
1667 n = Notation(name, publicId, systemId)
1668 n.ownerDocument = self
1669 return n
1670
1671 def getElementById(self, id):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +00001672 if id in self._id_cache:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001673 return self._id_cache[id]
1674 if not (self._elem_info or self._magic_id_count):
1675 return None
1676
1677 stack = self._id_search_stack
1678 if stack is None:
1679 # we never searched before, or the cache has been cleared
1680 stack = [self.documentElement]
1681 self._id_search_stack = stack
1682 elif not stack:
1683 # Previous search was completed and cache is still valid;
1684 # no matching node.
1685 return None
1686
1687 result = None
1688 while stack:
1689 node = stack.pop()
1690 # add child elements to stack for continued searching
1691 stack.extend([child for child in node.childNodes
1692 if child.nodeType in _nodeTypes_with_children])
1693 # check this node
1694 info = self._get_elem_info(node)
1695 if info:
1696 # We have to process all ID attributes before
1697 # returning in order to get all the attributes set to
1698 # be IDs using Element.setIdAttribute*().
1699 for attr in node.attributes.values():
1700 if attr.namespaceURI:
1701 if info.isIdNS(attr.namespaceURI, attr.localName):
1702 self._id_cache[attr.value] = node
1703 if attr.value == id:
1704 result = node
1705 elif not node._magic_id_nodes:
1706 break
1707 elif info.isId(attr.name):
1708 self._id_cache[attr.value] = node
1709 if attr.value == id:
1710 result = node
1711 elif not node._magic_id_nodes:
1712 break
1713 elif attr._is_id:
1714 self._id_cache[attr.value] = node
1715 if attr.value == id:
1716 result = node
1717 elif node._magic_id_nodes == 1:
1718 break
1719 elif node._magic_id_nodes:
1720 for attr in node.attributes.values():
1721 if attr._is_id:
1722 self._id_cache[attr.value] = node
1723 if attr.value == id:
1724 result = node
1725 if result is not None:
1726 break
1727 return result
1728
Fred Drake1f549022000-09-24 05:21:58 +00001729 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001730 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drakefbe7b4f2001-07-04 06:25:53 +00001731
1732 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001733 return _get_elements_by_tagName_ns_helper(
1734 self, namespaceURI, localName, NodeList())
1735
1736 def isSupported(self, feature, version):
1737 return self.implementation.hasFeature(feature, version)
1738
1739 def importNode(self, node, deep):
1740 if node.nodeType == Node.DOCUMENT_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001741 raise xml.dom.NotSupportedErr("cannot import document nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001742 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001743 raise xml.dom.NotSupportedErr("cannot import document type nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001744 return _clone_node(node, deep, self)
Fred Drake55c38192000-06-29 19:39:57 +00001745
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001746 def writexml(self, writer, indent="", addindent="", newl="",
1747 encoding = None):
1748 if encoding is None:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001749 writer.write('<?xml version="1.0" ?>'+newl)
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001750 else:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001751 writer.write('<?xml version="1.0" encoding="%s"?>%s' % (encoding, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001752 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001753 node.writexml(writer, indent, addindent, newl)
Fred Drake55c38192000-06-29 19:39:57 +00001754
Martin v. Löwis787354c2003-01-25 15:28:29 +00001755 # DOM Level 3 (WD 9 April 2002)
1756
1757 def renameNode(self, n, namespaceURI, name):
1758 if n.ownerDocument is not self:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001759 raise xml.dom.WrongDocumentErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001760 "cannot rename nodes from other documents;\n"
1761 "expected %s,\nfound %s" % (self, n.ownerDocument))
1762 if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001763 raise xml.dom.NotSupportedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001764 "renameNode() only applies to element and attribute nodes")
1765 if namespaceURI != EMPTY_NAMESPACE:
1766 if ':' in name:
1767 prefix, localName = name.split(':', 1)
1768 if ( prefix == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001769 and namespaceURI != xml.dom.XMLNS_NAMESPACE):
1770 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001771 "illegal use of 'xmlns' prefix")
1772 else:
1773 if ( name == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001774 and namespaceURI != xml.dom.XMLNS_NAMESPACE
Martin v. Löwis787354c2003-01-25 15:28:29 +00001775 and n.nodeType == Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001776 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001777 "illegal use of the 'xmlns' attribute")
1778 prefix = None
1779 localName = name
1780 else:
1781 prefix = None
1782 localName = None
1783 if n.nodeType == Node.ATTRIBUTE_NODE:
1784 element = n.ownerElement
1785 if element is not None:
1786 is_id = n._is_id
1787 element.removeAttributeNode(n)
1788 else:
1789 element = None
1790 # avoid __setattr__
1791 d = n.__dict__
1792 d['prefix'] = prefix
1793 d['localName'] = localName
1794 d['namespaceURI'] = namespaceURI
1795 d['nodeName'] = name
1796 if n.nodeType == Node.ELEMENT_NODE:
1797 d['tagName'] = name
1798 else:
1799 # attribute node
1800 d['name'] = name
1801 if element is not None:
1802 element.setAttributeNode(n)
1803 if is_id:
1804 element.setIdAttributeNode(n)
1805 # It's not clear from a semantic perspective whether we should
1806 # call the user data handlers for the NODE_RENAMED event since
1807 # we're re-using the existing node. The draft spec has been
1808 # interpreted as meaning "no, don't call the handler unless a
1809 # new node is created."
1810 return n
1811
1812defproperty(Document, "documentElement",
1813 doc="Top-level element of this document.")
1814
1815
1816def _clone_node(node, deep, newOwnerDocument):
1817 """
1818 Clone a node and give it the new owner document.
1819 Called by Node.cloneNode and Document.importNode
1820 """
1821 if node.ownerDocument.isSameNode(newOwnerDocument):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001822 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001823 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001824 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001825 if node.nodeType == Node.ELEMENT_NODE:
1826 clone = newOwnerDocument.createElementNS(node.namespaceURI,
1827 node.nodeName)
1828 for attr in node.attributes.values():
1829 clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
1830 a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)
1831 a.specified = attr.specified
1832
1833 if deep:
1834 for child in node.childNodes:
1835 c = _clone_node(child, deep, newOwnerDocument)
1836 clone.appendChild(c)
1837
1838 elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
1839 clone = newOwnerDocument.createDocumentFragment()
1840 if deep:
1841 for child in node.childNodes:
1842 c = _clone_node(child, deep, newOwnerDocument)
1843 clone.appendChild(c)
1844
1845 elif node.nodeType == Node.TEXT_NODE:
1846 clone = newOwnerDocument.createTextNode(node.data)
1847 elif node.nodeType == Node.CDATA_SECTION_NODE:
1848 clone = newOwnerDocument.createCDATASection(node.data)
1849 elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
1850 clone = newOwnerDocument.createProcessingInstruction(node.target,
1851 node.data)
1852 elif node.nodeType == Node.COMMENT_NODE:
1853 clone = newOwnerDocument.createComment(node.data)
1854 elif node.nodeType == Node.ATTRIBUTE_NODE:
1855 clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
1856 node.nodeName)
1857 clone.specified = True
1858 clone.value = node.value
1859 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
1860 assert node.ownerDocument is not newOwnerDocument
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001861 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001862 clone = newOwnerDocument.implementation.createDocumentType(
1863 node.name, node.publicId, node.systemId)
1864 clone.ownerDocument = newOwnerDocument
1865 if deep:
1866 clone.entities._seq = []
1867 clone.notations._seq = []
1868 for n in node.notations._seq:
1869 notation = Notation(n.nodeName, n.publicId, n.systemId)
1870 notation.ownerDocument = newOwnerDocument
1871 clone.notations._seq.append(notation)
1872 if hasattr(n, '_call_user_data_handler'):
1873 n._call_user_data_handler(operation, n, notation)
1874 for e in node.entities._seq:
1875 entity = Entity(e.nodeName, e.publicId, e.systemId,
1876 e.notationName)
1877 entity.actualEncoding = e.actualEncoding
1878 entity.encoding = e.encoding
1879 entity.version = e.version
1880 entity.ownerDocument = newOwnerDocument
1881 clone.entities._seq.append(entity)
1882 if hasattr(e, '_call_user_data_handler'):
1883 e._call_user_data_handler(operation, n, entity)
1884 else:
1885 # Note the cloning of Document and DocumentType nodes is
1886 # implemenetation specific. minidom handles those cases
1887 # directly in the cloneNode() methods.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001888 raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001889
1890 # Check for _call_user_data_handler() since this could conceivably
1891 # used with other DOM implementations (one of the FourThought
1892 # DOMs, perhaps?).
1893 if hasattr(node, '_call_user_data_handler'):
1894 node._call_user_data_handler(operation, node, clone)
1895 return clone
1896
1897
1898def _nssplit(qualifiedName):
1899 fields = qualifiedName.split(':', 1)
1900 if len(fields) == 2:
1901 return fields
1902 else:
1903 return (None, fields[0])
1904
1905
Martin v. Löwis787354c2003-01-25 15:28:29 +00001906def _do_pulldom_parse(func, args, kwargs):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001907 events = func(*args, **kwargs)
Fred Drake1f549022000-09-24 05:21:58 +00001908 toktype, rootNode = events.getEvent()
1909 events.expandNode(rootNode)
Martin v. Löwisb417be22001-02-06 01:16:06 +00001910 events.clear()
Fred Drake55c38192000-06-29 19:39:57 +00001911 return rootNode
1912
Martin v. Löwis787354c2003-01-25 15:28:29 +00001913def parse(file, parser=None, bufsize=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001914 """Parse a file into a DOM by filename or file object."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001915 if parser is None and not bufsize:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001916 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001917 return expatbuilder.parse(file)
1918 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001919 from xml.dom import pulldom
Raymond Hettingerff41c482003-04-06 09:01:11 +00001920 return _do_pulldom_parse(pulldom.parse, (file,),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001921 {'parser': parser, 'bufsize': bufsize})
Fred Drake55c38192000-06-29 19:39:57 +00001922
Martin v. Löwis787354c2003-01-25 15:28:29 +00001923def parseString(string, parser=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001924 """Parse a file into a DOM from a string."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001925 if parser is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001926 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001927 return expatbuilder.parseString(string)
1928 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001929 from xml.dom import pulldom
Martin v. Löwis787354c2003-01-25 15:28:29 +00001930 return _do_pulldom_parse(pulldom.parseString, (string,),
1931 {'parser': parser})
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001932
Martin v. Löwis787354c2003-01-25 15:28:29 +00001933def getDOMImplementation(features=None):
1934 if features:
Christian Heimesc9543e42007-11-28 08:28:28 +00001935 if isinstance(features, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001936 features = domreg._parse_feature_string(features)
1937 for f, v in features:
1938 if not Document.implementation.hasFeature(f, v):
1939 return None
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001940 return Document.implementation