blob: 1beae0cffa52be0698120c16fcf6c0419c25b198 [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
Georg Brandlfe991052009-09-16 15:54:04 +000046 def toxml(self, encoding=None):
Martin v. Löwis7d650ca2002-06-30 15:05:00 +000047 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:
R. David Murraydc6da8a2009-04-09 22:16:43 +0000182 if not child.data:
183 # empty text node; discard
184 if L:
185 L[-1].nextSibling = child.nextSibling
186 if child.nextSibling:
187 child.nextSibling.previousSibling = child.previousSibling
188 child.unlink()
189 elif L and L[-1].nodeType == child.nodeType:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000190 # collapse text node
191 node = L[-1]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000192 node.data = node.data + child.data
Fred Drake4ccf4a12000-11-21 22:02:22 +0000193 node.nextSibling = child.nextSibling
R. David Murraydc6da8a2009-04-09 22:16:43 +0000194 if child.nextSibling:
195 child.nextSibling.previousSibling = node
Fred Drake4ccf4a12000-11-21 22:02:22 +0000196 child.unlink()
R. David Murraydc6da8a2009-04-09 22:16:43 +0000197 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000198 L.append(child)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000199 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000200 L.append(child)
201 if child.nodeType == Node.ELEMENT_NODE:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000202 child.normalize()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000203 self.childNodes[:] = L
Paul Prescod73678da2000-07-01 04:58:47 +0000204
Fred Drake1f549022000-09-24 05:21:58 +0000205 def cloneNode(self, deep):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000206 return _clone_node(self, deep, self.ownerDocument or self)
Fred Drake55c38192000-06-29 19:39:57 +0000207
Martin v. Löwis787354c2003-01-25 15:28:29 +0000208 def isSupported(self, feature, version):
209 return self.ownerDocument.implementation.hasFeature(feature, version)
210
211 def _get_localName(self):
212 # Overridden in Element and Attr where localName can be Non-Null
213 return None
214
215 # Node interfaces from Level 3 (WD 9 April 2002)
Fred Drake25239772001-02-02 19:40:19 +0000216
217 def isSameNode(self, other):
218 return self is other
219
Martin v. Löwis787354c2003-01-25 15:28:29 +0000220 def getInterface(self, feature):
221 if self.isSupported(feature, None):
222 return self
223 else:
224 return None
225
226 # The "user data" functions use a dictionary that is only present
227 # if some user data has been set, so be careful not to assume it
228 # exists.
229
230 def getUserData(self, key):
231 try:
232 return self._user_data[key][0]
233 except (AttributeError, KeyError):
234 return None
235
236 def setUserData(self, key, data, handler):
237 old = None
238 try:
239 d = self._user_data
240 except AttributeError:
241 d = {}
242 self._user_data = d
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000243 if key in d:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000244 old = d[key][0]
245 if data is None:
246 # ignore handlers passed for None
247 handler = None
248 if old is not None:
249 del d[key]
250 else:
251 d[key] = (data, handler)
252 return old
253
254 def _call_user_data_handler(self, operation, src, dst):
255 if hasattr(self, "_user_data"):
Brett Cannon861fd6f2007-02-21 22:05:37 +0000256 for key, (data, handler) in list(self._user_data.items()):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000257 if handler is not None:
258 handler.handle(operation, key, data, src, dst)
259
Fred Drake25239772001-02-02 19:40:19 +0000260 # minidom-specific API:
261
Fred Drake1f549022000-09-24 05:21:58 +0000262 def unlink(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000263 self.parentNode = self.ownerDocument = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000264 if self.childNodes:
265 for child in self.childNodes:
266 child.unlink()
267 self.childNodes = NodeList()
Paul Prescod4221ff02000-10-13 20:11:42 +0000268 self.previousSibling = None
269 self.nextSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000270
Kristján Valur Jónsson17173cf2010-06-09 08:13:42 +0000271 # A Node is its own context manager, to ensure that an unlink() call occurs.
272 # This is similar to how a file object works.
273 def __enter__(self):
274 return self
275
276 def __exit__(self, et, ev, tb):
277 self.unlink()
278
Martin v. Löwis787354c2003-01-25 15:28:29 +0000279defproperty(Node, "firstChild", doc="First child node, or None.")
280defproperty(Node, "lastChild", doc="Last child node, or None.")
281defproperty(Node, "localName", doc="Namespace-local name of this node.")
282
283
284def _append_child(self, node):
285 # fast path with less checks; usable by DOM builders if careful
286 childNodes = self.childNodes
287 if childNodes:
288 last = childNodes[-1]
289 node.__dict__["previousSibling"] = last
290 last.__dict__["nextSibling"] = node
291 childNodes.append(node)
292 node.__dict__["parentNode"] = self
293
294def _in_document(node):
295 # return True iff node is part of a document tree
296 while node is not None:
297 if node.nodeType == Node.DOCUMENT_NODE:
298 return True
299 node = node.parentNode
300 return False
Fred Drake55c38192000-06-29 19:39:57 +0000301
Fred Drake1f549022000-09-24 05:21:58 +0000302def _write_data(writer, data):
Fred Drake55c38192000-06-29 19:39:57 +0000303 "Writes datachars to writer."
Martin v. Löwis787354c2003-01-25 15:28:29 +0000304 data = data.replace("&", "&amp;").replace("<", "&lt;")
305 data = data.replace("\"", "&quot;").replace(">", "&gt;")
Fred Drake55c38192000-06-29 19:39:57 +0000306 writer.write(data)
307
Martin v. Löwis787354c2003-01-25 15:28:29 +0000308def _get_elements_by_tagName_helper(parent, name, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000309 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000310 if node.nodeType == Node.ELEMENT_NODE and \
311 (name == "*" or node.tagName == name):
312 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000313 _get_elements_by_tagName_helper(node, name, rc)
Fred Drake55c38192000-06-29 19:39:57 +0000314 return rc
315
Martin v. Löwis787354c2003-01-25 15:28:29 +0000316def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000317 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000318 if node.nodeType == Node.ELEMENT_NODE:
Martin v. Löwised525fb2001-06-03 14:06:42 +0000319 if ((localName == "*" or node.localName == localName) and
Fred Drake1f549022000-09-24 05:21:58 +0000320 (nsURI == "*" or node.namespaceURI == nsURI)):
321 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000322 _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000323 return rc
Fred Drake55c38192000-06-29 19:39:57 +0000324
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000325class DocumentFragment(Node):
326 nodeType = Node.DOCUMENT_FRAGMENT_NODE
327 nodeName = "#document-fragment"
328 nodeValue = None
329 attributes = None
330 parentNode = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000331 _child_node_types = (Node.ELEMENT_NODE,
332 Node.TEXT_NODE,
333 Node.CDATA_SECTION_NODE,
334 Node.ENTITY_REFERENCE_NODE,
335 Node.PROCESSING_INSTRUCTION_NODE,
336 Node.COMMENT_NODE,
337 Node.NOTATION_NODE)
338
339 def __init__(self):
340 self.childNodes = NodeList()
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000341
342
Fred Drake55c38192000-06-29 19:39:57 +0000343class Attr(Node):
Fred Drake1f549022000-09-24 05:21:58 +0000344 nodeType = Node.ATTRIBUTE_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +0000345 attributes = None
346 ownerElement = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000347 specified = False
348 _is_id = False
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000349
Martin v. Löwis787354c2003-01-25 15:28:29 +0000350 _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE)
351
352 def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None,
353 prefix=None):
Fred Drake55c38192000-06-29 19:39:57 +0000354 # skip setattr for performance
Fred Drake4ccf4a12000-11-21 22:02:22 +0000355 d = self.__dict__
Fred Drake4ccf4a12000-11-21 22:02:22 +0000356 d["nodeName"] = d["name"] = qName
357 d["namespaceURI"] = namespaceURI
358 d["prefix"] = prefix
Martin v. Löwis787354c2003-01-25 15:28:29 +0000359 d['childNodes'] = NodeList()
360
361 # Add the single child node that represents the value of the attr
362 self.childNodes.append(Text())
363
Paul Prescod73678da2000-07-01 04:58:47 +0000364 # nodeValue and value are set elsewhere
Fred Drake55c38192000-06-29 19:39:57 +0000365
Martin v. Löwis787354c2003-01-25 15:28:29 +0000366 def _get_localName(self):
Alex Martelli0ee43512006-08-21 19:53:20 +0000367 if 'localName' in self.__dict__:
Guido van Rossum3e1f85e2007-07-27 18:03:11 +0000368 return self.__dict__['localName']
Martin v. Löwis787354c2003-01-25 15:28:29 +0000369 return self.nodeName.split(":", 1)[-1]
370
371 def _get_name(self):
372 return self.name
373
374 def _get_specified(self):
375 return self.specified
376
Fred Drake1f549022000-09-24 05:21:58 +0000377 def __setattr__(self, name, value):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000378 d = self.__dict__
Fred Drake1f549022000-09-24 05:21:58 +0000379 if name in ("value", "nodeValue"):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000380 d["value"] = d["nodeValue"] = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000381 d2 = self.childNodes[0].__dict__
382 d2["data"] = d2["nodeValue"] = value
383 if self.ownerElement is not None:
384 _clear_id_cache(self.ownerElement)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000385 elif name in ("name", "nodeName"):
386 d["name"] = d["nodeName"] = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000387 if self.ownerElement is not None:
388 _clear_id_cache(self.ownerElement)
Fred Drake55c38192000-06-29 19:39:57 +0000389 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000390 d[name] = value
Fred Drake55c38192000-06-29 19:39:57 +0000391
Martin v. Löwis995359c2003-01-26 08:59:32 +0000392 def _set_prefix(self, prefix):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000393 nsuri = self.namespaceURI
Martin v. Löwis995359c2003-01-26 08:59:32 +0000394 if prefix == "xmlns":
395 if nsuri and nsuri != XMLNS_NAMESPACE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000396 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000397 "illegal use of 'xmlns' prefix for the wrong namespace")
398 d = self.__dict__
399 d['prefix'] = prefix
400 if prefix is None:
401 newName = self.localName
402 else:
Martin v. Löwis995359c2003-01-26 08:59:32 +0000403 newName = "%s:%s" % (prefix, self.localName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000404 if self.ownerElement:
405 _clear_id_cache(self.ownerElement)
406 d['nodeName'] = d['name'] = newName
407
408 def _set_value(self, value):
409 d = self.__dict__
410 d['value'] = d['nodeValue'] = value
411 if self.ownerElement:
412 _clear_id_cache(self.ownerElement)
413 self.childNodes[0].data = value
414
415 def unlink(self):
416 # This implementation does not call the base implementation
417 # since most of that is not needed, and the expense of the
418 # method call is not warranted. We duplicate the removal of
419 # children, but that's all we needed from the base class.
420 elem = self.ownerElement
421 if elem is not None:
422 del elem._attrs[self.nodeName]
423 del elem._attrsNS[(self.namespaceURI, self.localName)]
424 if self._is_id:
425 self._is_id = False
426 elem._magic_id_nodes -= 1
427 self.ownerDocument._magic_id_count -= 1
428 for child in self.childNodes:
429 child.unlink()
430 del self.childNodes[:]
431
432 def _get_isId(self):
433 if self._is_id:
434 return True
435 doc = self.ownerDocument
436 elem = self.ownerElement
437 if doc is None or elem is None:
438 return False
439
440 info = doc._get_elem_info(elem)
441 if info is None:
442 return False
443 if self.namespaceURI:
444 return info.isIdNS(self.namespaceURI, self.localName)
445 else:
446 return info.isId(self.nodeName)
447
448 def _get_schemaType(self):
449 doc = self.ownerDocument
450 elem = self.ownerElement
451 if doc is None or elem is None:
452 return _no_type
453
454 info = doc._get_elem_info(elem)
455 if info is None:
456 return _no_type
457 if self.namespaceURI:
458 return info.getAttributeTypeNS(self.namespaceURI, self.localName)
459 else:
460 return info.getAttributeType(self.nodeName)
461
462defproperty(Attr, "isId", doc="True if this attribute is an ID.")
463defproperty(Attr, "localName", doc="Namespace-local name of this attribute.")
464defproperty(Attr, "schemaType", doc="Schema type for this attribute.")
Fred Drake4ccf4a12000-11-21 22:02:22 +0000465
Fred Drakef7cf40d2000-12-14 18:16:11 +0000466
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000467class NamedNodeMap(object):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000468 """The attribute list is a transient interface to the underlying
469 dictionaries. Mutations here will change the underlying element's
Fred Drakef7cf40d2000-12-14 18:16:11 +0000470 dictionary.
471
472 Ordering is imposed artificially and does not reflect the order of
473 attributes as found in an input document.
474 """
Fred Drake4ccf4a12000-11-21 22:02:22 +0000475
Martin v. Löwis787354c2003-01-25 15:28:29 +0000476 __slots__ = ('_attrs', '_attrsNS', '_ownerElement')
477
Fred Drake2998a552001-12-06 18:27:48 +0000478 def __init__(self, attrs, attrsNS, ownerElement):
Fred Drake1f549022000-09-24 05:21:58 +0000479 self._attrs = attrs
480 self._attrsNS = attrsNS
Fred Drake2998a552001-12-06 18:27:48 +0000481 self._ownerElement = ownerElement
Fred Drakef7cf40d2000-12-14 18:16:11 +0000482
Martin v. Löwis787354c2003-01-25 15:28:29 +0000483 def _get_length(self):
484 return len(self._attrs)
Fred Drake55c38192000-06-29 19:39:57 +0000485
Fred Drake1f549022000-09-24 05:21:58 +0000486 def item(self, index):
Fred Drake55c38192000-06-29 19:39:57 +0000487 try:
Brett Cannon861fd6f2007-02-21 22:05:37 +0000488 return self[list(self._attrs.keys())[index]]
Fred Drake55c38192000-06-29 19:39:57 +0000489 except IndexError:
490 return None
Fred Drake55c38192000-06-29 19:39:57 +0000491
Fred Drake1f549022000-09-24 05:21:58 +0000492 def items(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000493 L = []
494 for node in self._attrs.values():
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000495 L.append((node.nodeName, node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000496 return L
Fred Drake1f549022000-09-24 05:21:58 +0000497
498 def itemsNS(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000499 L = []
500 for node in self._attrs.values():
Fred Drake49a5d032001-11-30 22:21:58 +0000501 L.append(((node.namespaceURI, node.localName), node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000502 return L
Fred Drake16f63292000-10-23 18:09:50 +0000503
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000504 def __contains__(self, key):
Christian Heimesc9543e42007-11-28 08:28:28 +0000505 if isinstance(key, str):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000506 return key in self._attrs
Martin v. Löwis787354c2003-01-25 15:28:29 +0000507 else:
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000508 return key in self._attrsNS
Martin v. Löwis787354c2003-01-25 15:28:29 +0000509
Fred Drake1f549022000-09-24 05:21:58 +0000510 def keys(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000511 return self._attrs.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000512
Fred Drake1f549022000-09-24 05:21:58 +0000513 def keysNS(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000514 return self._attrsNS.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000515
Fred Drake1f549022000-09-24 05:21:58 +0000516 def values(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000517 return self._attrs.values()
Fred Drake55c38192000-06-29 19:39:57 +0000518
Martin v. Löwis787354c2003-01-25 15:28:29 +0000519 def get(self, name, value=None):
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000520 return self._attrs.get(name, value)
521
Martin v. Löwis787354c2003-01-25 15:28:29 +0000522 __len__ = _get_length
Fred Drake55c38192000-06-29 19:39:57 +0000523
Mark Dickinsona56c4672009-01-27 18:17:45 +0000524 def _cmp(self, other):
Fred Drake1f549022000-09-24 05:21:58 +0000525 if self._attrs is getattr(other, "_attrs", None):
Fred Drake55c38192000-06-29 19:39:57 +0000526 return 0
Fred Drake16f63292000-10-23 18:09:50 +0000527 else:
Mark Dickinsona56c4672009-01-27 18:17:45 +0000528 return (id(self) > id(other)) - (id(self) < id(other))
529
530 def __eq__(self, other):
531 return self._cmp(other) == 0
532
533 def __ge__(self, other):
534 return self._cmp(other) >= 0
535
536 def __gt__(self, other):
537 return self._cmp(other) > 0
538
539 def __le__(self, other):
540 return self._cmp(other) <= 0
541
542 def __lt__(self, other):
543 return self._cmp(other) < 0
544
545 def __ne__(self, other):
546 return self._cmp(other) != 0
Fred Drake55c38192000-06-29 19:39:57 +0000547
Fred Drake1f549022000-09-24 05:21:58 +0000548 def __getitem__(self, attname_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000549 if isinstance(attname_or_tuple, tuple):
Paul Prescod73678da2000-07-01 04:58:47 +0000550 return self._attrsNS[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000551 else:
Paul Prescod73678da2000-07-01 04:58:47 +0000552 return self._attrs[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000553
Paul Prescod1e688272000-07-01 19:21:47 +0000554 # same as set
Fred Drake1f549022000-09-24 05:21:58 +0000555 def __setitem__(self, attname, value):
Christian Heimesc9543e42007-11-28 08:28:28 +0000556 if isinstance(value, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000557 try:
558 node = self._attrs[attname]
559 except KeyError:
560 node = Attr(attname)
561 node.ownerDocument = self._ownerElement.ownerDocument
Martin v. Löwis995359c2003-01-26 08:59:32 +0000562 self.setNamedItem(node)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000563 node.value = value
Paul Prescod1e688272000-07-01 19:21:47 +0000564 else:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000565 if not isinstance(value, Attr):
Collin Winter70e79802007-08-24 18:57:22 +0000566 raise TypeError("value must be a string or Attr object")
Fred Drake1f549022000-09-24 05:21:58 +0000567 node = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000568 self.setNamedItem(node)
569
570 def getNamedItem(self, name):
571 try:
572 return self._attrs[name]
573 except KeyError:
574 return None
575
576 def getNamedItemNS(self, namespaceURI, localName):
577 try:
578 return self._attrsNS[(namespaceURI, localName)]
579 except KeyError:
580 return None
581
582 def removeNamedItem(self, name):
583 n = self.getNamedItem(name)
584 if n is not None:
585 _clear_id_cache(self._ownerElement)
586 del self._attrs[n.nodeName]
587 del self._attrsNS[(n.namespaceURI, n.localName)]
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000588 if 'ownerElement' in n.__dict__:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000589 n.__dict__['ownerElement'] = None
590 return n
591 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000592 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000593
594 def removeNamedItemNS(self, namespaceURI, localName):
595 n = self.getNamedItemNS(namespaceURI, localName)
596 if n is not None:
597 _clear_id_cache(self._ownerElement)
598 del self._attrsNS[(n.namespaceURI, n.localName)]
599 del self._attrs[n.nodeName]
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000600 if 'ownerElement' in n.__dict__:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000601 n.__dict__['ownerElement'] = None
602 return n
603 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000604 raise xml.dom.NotFoundErr()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000605
606 def setNamedItem(self, node):
Andrew M. Kuchlingbc8f72c2001-02-21 01:30:26 +0000607 if not isinstance(node, Attr):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000608 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000609 "%s cannot be child of %s" % (repr(node), repr(self)))
Fred Drakef7cf40d2000-12-14 18:16:11 +0000610 old = self._attrs.get(node.name)
Paul Prescod1e688272000-07-01 19:21:47 +0000611 if old:
612 old.unlink()
Fred Drake1f549022000-09-24 05:21:58 +0000613 self._attrs[node.name] = node
614 self._attrsNS[(node.namespaceURI, node.localName)] = node
Fred Drake2998a552001-12-06 18:27:48 +0000615 node.ownerElement = self._ownerElement
Martin v. Löwis787354c2003-01-25 15:28:29 +0000616 _clear_id_cache(node.ownerElement)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000617 return old
618
619 def setNamedItemNS(self, node):
620 return self.setNamedItem(node)
Paul Prescod73678da2000-07-01 04:58:47 +0000621
Fred Drake1f549022000-09-24 05:21:58 +0000622 def __delitem__(self, attname_or_tuple):
623 node = self[attname_or_tuple]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000624 _clear_id_cache(node.ownerElement)
Paul Prescod73678da2000-07-01 04:58:47 +0000625 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000626
627 def __getstate__(self):
628 return self._attrs, self._attrsNS, self._ownerElement
629
630 def __setstate__(self, state):
631 self._attrs, self._attrsNS, self._ownerElement = state
632
633defproperty(NamedNodeMap, "length",
634 doc="Number of nodes in the NamedNodeMap.")
Fred Drakef7cf40d2000-12-14 18:16:11 +0000635
636AttributeList = NamedNodeMap
637
Fred Drake1f549022000-09-24 05:21:58 +0000638
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000639class TypeInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000640 __slots__ = 'namespace', 'name'
641
642 def __init__(self, namespace, name):
643 self.namespace = namespace
644 self.name = name
645
646 def __repr__(self):
647 if self.namespace:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000648 return "<TypeInfo %r (from %r)>" % (self.name, self.namespace)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000649 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000650 return "<TypeInfo %r>" % self.name
Martin v. Löwis787354c2003-01-25 15:28:29 +0000651
652 def _get_name(self):
653 return self.name
654
655 def _get_namespace(self):
656 return self.namespace
657
658_no_type = TypeInfo(None, None)
659
Martin v. Löwisa2fda0d2000-10-07 12:10:28 +0000660class Element(Node):
Fred Drake1f549022000-09-24 05:21:58 +0000661 nodeType = Node.ELEMENT_NODE
Martin v. Löwis787354c2003-01-25 15:28:29 +0000662 nodeValue = None
663 schemaType = _no_type
664
665 _magic_id_nodes = 0
666
667 _child_node_types = (Node.ELEMENT_NODE,
668 Node.PROCESSING_INSTRUCTION_NODE,
669 Node.COMMENT_NODE,
670 Node.TEXT_NODE,
671 Node.CDATA_SECTION_NODE,
672 Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000673
Fred Drake49a5d032001-11-30 22:21:58 +0000674 def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None,
Fred Drake1f549022000-09-24 05:21:58 +0000675 localName=None):
Fred Drake55c38192000-06-29 19:39:57 +0000676 self.tagName = self.nodeName = tagName
Fred Drake1f549022000-09-24 05:21:58 +0000677 self.prefix = prefix
678 self.namespaceURI = namespaceURI
Martin v. Löwis787354c2003-01-25 15:28:29 +0000679 self.childNodes = NodeList()
Fred Drake55c38192000-06-29 19:39:57 +0000680
Fred Drake4ccf4a12000-11-21 22:02:22 +0000681 self._attrs = {} # attributes are double-indexed:
682 self._attrsNS = {} # tagName -> Attribute
683 # URI,localName -> Attribute
684 # in the future: consider lazy generation
685 # of attribute objects this is too tricky
686 # for now because of headaches with
687 # namespaces.
688
Martin v. Löwis787354c2003-01-25 15:28:29 +0000689 def _get_localName(self):
Alex Martelli0ee43512006-08-21 19:53:20 +0000690 if 'localName' in self.__dict__:
Guido van Rossum3e1f85e2007-07-27 18:03:11 +0000691 return self.__dict__['localName']
Martin v. Löwis787354c2003-01-25 15:28:29 +0000692 return self.tagName.split(":", 1)[-1]
693
694 def _get_tagName(self):
695 return self.tagName
Fred Drake4ccf4a12000-11-21 22:02:22 +0000696
697 def unlink(self):
Brett Cannon861fd6f2007-02-21 22:05:37 +0000698 for attr in list(self._attrs.values()):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000699 attr.unlink()
700 self._attrs = None
701 self._attrsNS = None
702 Node.unlink(self)
Fred Drake55c38192000-06-29 19:39:57 +0000703
Fred Drake1f549022000-09-24 05:21:58 +0000704 def getAttribute(self, attname):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000705 try:
706 return self._attrs[attname].value
707 except KeyError:
708 return ""
Fred Drake55c38192000-06-29 19:39:57 +0000709
Fred Drake1f549022000-09-24 05:21:58 +0000710 def getAttributeNS(self, namespaceURI, localName):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000711 try:
712 return self._attrsNS[(namespaceURI, localName)].value
713 except KeyError:
714 return ""
Fred Drake1f549022000-09-24 05:21:58 +0000715
716 def setAttribute(self, attname, value):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000717 attr = self.getAttributeNode(attname)
718 if attr is None:
719 attr = Attr(attname)
720 # for performance
721 d = attr.__dict__
722 d["value"] = d["nodeValue"] = value
723 d["ownerDocument"] = self.ownerDocument
724 self.setAttributeNode(attr)
725 elif value != attr.value:
726 d = attr.__dict__
727 d["value"] = d["nodeValue"] = value
728 if attr.isId:
729 _clear_id_cache(self)
Fred Drake55c38192000-06-29 19:39:57 +0000730
Fred Drake1f549022000-09-24 05:21:58 +0000731 def setAttributeNS(self, namespaceURI, qualifiedName, value):
732 prefix, localname = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000733 attr = self.getAttributeNodeNS(namespaceURI, localname)
734 if attr is None:
735 # for performance
736 attr = Attr(qualifiedName, namespaceURI, localname, prefix)
737 d = attr.__dict__
738 d["prefix"] = prefix
739 d["nodeName"] = qualifiedName
740 d["value"] = d["nodeValue"] = value
741 d["ownerDocument"] = self.ownerDocument
742 self.setAttributeNode(attr)
743 else:
744 d = attr.__dict__
745 if value != attr.value:
746 d["value"] = d["nodeValue"] = value
747 if attr.isId:
748 _clear_id_cache(self)
749 if attr.prefix != prefix:
750 d["prefix"] = prefix
751 d["nodeName"] = qualifiedName
Fred Drake55c38192000-06-29 19:39:57 +0000752
Fred Drake1f549022000-09-24 05:21:58 +0000753 def getAttributeNode(self, attrname):
754 return self._attrs.get(attrname)
Paul Prescod73678da2000-07-01 04:58:47 +0000755
Fred Drake1f549022000-09-24 05:21:58 +0000756 def getAttributeNodeNS(self, namespaceURI, localName):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000757 return self._attrsNS.get((namespaceURI, localName))
Paul Prescod73678da2000-07-01 04:58:47 +0000758
Fred Drake1f549022000-09-24 05:21:58 +0000759 def setAttributeNode(self, attr):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000760 if attr.ownerElement not in (None, self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000761 raise xml.dom.InuseAttributeErr("attribute node already owned")
Martin v. Löwis787354c2003-01-25 15:28:29 +0000762 old1 = self._attrs.get(attr.name, None)
763 if old1 is not None:
764 self.removeAttributeNode(old1)
765 old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None)
766 if old2 is not None and old2 is not old1:
767 self.removeAttributeNode(old2)
768 _set_attribute_node(self, attr)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000769
Martin v. Löwis787354c2003-01-25 15:28:29 +0000770 if old1 is not attr:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000771 # It might have already been part of this node, in which case
772 # it doesn't represent a change, and should not be returned.
Martin v. Löwis787354c2003-01-25 15:28:29 +0000773 return old1
774 if old2 is not attr:
775 return old2
Fred Drake55c38192000-06-29 19:39:57 +0000776
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000777 setAttributeNodeNS = setAttributeNode
778
Fred Drake1f549022000-09-24 05:21:58 +0000779 def removeAttribute(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000780 try:
781 attr = self._attrs[name]
782 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000783 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000784 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000785
Fred Drake1f549022000-09-24 05:21:58 +0000786 def removeAttributeNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000787 try:
788 attr = self._attrsNS[(namespaceURI, localName)]
789 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000790 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000791 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000792
Fred Drake1f549022000-09-24 05:21:58 +0000793 def removeAttributeNode(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000794 if node is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000795 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000796 try:
797 self._attrs[node.name]
798 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000799 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000800 _clear_id_cache(self)
Paul Prescod73678da2000-07-01 04:58:47 +0000801 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000802 # Restore this since the node is still useful and otherwise
803 # unlinked
804 node.ownerDocument = self.ownerDocument
Fred Drake16f63292000-10-23 18:09:50 +0000805
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000806 removeAttributeNodeNS = removeAttributeNode
807
Martin v. Löwis156c3372000-12-28 18:40:56 +0000808 def hasAttribute(self, name):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000809 return name in self._attrs
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000810
Martin v. Löwis156c3372000-12-28 18:40:56 +0000811 def hasAttributeNS(self, namespaceURI, localName):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000812 return (namespaceURI, localName) in self._attrsNS
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000813
Fred Drake1f549022000-09-24 05:21:58 +0000814 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000815 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000816
Fred Drake1f549022000-09-24 05:21:58 +0000817 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000818 return _get_elements_by_tagName_ns_helper(
819 self, namespaceURI, localName, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000820
Fred Drake1f549022000-09-24 05:21:58 +0000821 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000822 return "<DOM Element: %s at %#x>" % (self.tagName, id(self))
Fred Drake55c38192000-06-29 19:39:57 +0000823
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000824 def writexml(self, writer, indent="", addindent="", newl=""):
825 # indent = current indentation
826 # addindent = indentation to add to higher levels
827 # newl = newline string
828 writer.write(indent+"<" + self.tagName)
Fred Drake16f63292000-10-23 18:09:50 +0000829
Fred Drake4ccf4a12000-11-21 22:02:22 +0000830 attrs = self._get_attributes()
Brett Cannon861fd6f2007-02-21 22:05:37 +0000831 a_names = sorted(attrs.keys())
Fred Drake55c38192000-06-29 19:39:57 +0000832
833 for a_name in a_names:
Fred Drake1f549022000-09-24 05:21:58 +0000834 writer.write(" %s=\"" % a_name)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000835 _write_data(writer, attrs[a_name].value)
Fred Drake55c38192000-06-29 19:39:57 +0000836 writer.write("\"")
837 if self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000838 writer.write(">%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000839 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000840 node.writexml(writer,indent+addindent,addindent,newl)
841 writer.write("%s</%s>%s" % (indent,self.tagName,newl))
Fred Drake55c38192000-06-29 19:39:57 +0000842 else:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000843 writer.write("/>%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000844
Fred Drake1f549022000-09-24 05:21:58 +0000845 def _get_attributes(self):
Fred Drake2998a552001-12-06 18:27:48 +0000846 return NamedNodeMap(self._attrs, self._attrsNS, self)
Fred Drake55c38192000-06-29 19:39:57 +0000847
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000848 def hasAttributes(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000849 if self._attrs:
850 return True
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000851 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000852 return False
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000853
Martin v. Löwis787354c2003-01-25 15:28:29 +0000854 # DOM Level 3 attributes, based on the 22 Oct 2002 draft
855
856 def setIdAttribute(self, name):
857 idAttr = self.getAttributeNode(name)
858 self.setIdAttributeNode(idAttr)
859
860 def setIdAttributeNS(self, namespaceURI, localName):
861 idAttr = self.getAttributeNodeNS(namespaceURI, localName)
862 self.setIdAttributeNode(idAttr)
863
864 def setIdAttributeNode(self, idAttr):
865 if idAttr is None or not self.isSameNode(idAttr.ownerElement):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000866 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000867 if _get_containing_entref(self) is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000868 raise xml.dom.NoModificationAllowedErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000869 if not idAttr._is_id:
870 idAttr.__dict__['_is_id'] = True
871 self._magic_id_nodes += 1
872 self.ownerDocument._magic_id_count += 1
873 _clear_id_cache(self)
874
875defproperty(Element, "attributes",
876 doc="NamedNodeMap of attributes on the element.")
877defproperty(Element, "localName",
878 doc="Namespace-local name of this element.")
879
880
881def _set_attribute_node(element, attr):
882 _clear_id_cache(element)
883 element._attrs[attr.name] = attr
884 element._attrsNS[(attr.namespaceURI, attr.localName)] = attr
885
886 # This creates a circular reference, but Element.unlink()
887 # breaks the cycle since the references to the attribute
888 # dictionaries are tossed.
889 attr.__dict__['ownerElement'] = element
890
891
892class Childless:
893 """Mixin that makes childless-ness easy to implement and avoids
894 the complexity of the Node methods that deal with children.
895 """
896
Fred Drake4ccf4a12000-11-21 22:02:22 +0000897 attributes = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000898 childNodes = EmptyNodeList()
899 firstChild = None
900 lastChild = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000901
Martin v. Löwis787354c2003-01-25 15:28:29 +0000902 def _get_firstChild(self):
903 return None
Fred Drake55c38192000-06-29 19:39:57 +0000904
Martin v. Löwis787354c2003-01-25 15:28:29 +0000905 def _get_lastChild(self):
906 return None
Fred Drake1f549022000-09-24 05:21:58 +0000907
Martin v. Löwis787354c2003-01-25 15:28:29 +0000908 def appendChild(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000909 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000910 self.nodeName + " nodes cannot have children")
911
912 def hasChildNodes(self):
913 return False
914
915 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000916 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000917 self.nodeName + " nodes do not have children")
918
919 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000920 raise xml.dom.NotFoundErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000921 self.nodeName + " nodes do not have children")
922
Andrew M. Kuchling688b9e32010-07-25 23:38:47 +0000923 def normalize(self):
924 # For childless nodes, normalize() has nothing to do.
925 pass
926
Martin v. Löwis787354c2003-01-25 15:28:29 +0000927 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000928 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000929 self.nodeName + " nodes do not have children")
930
931
932class ProcessingInstruction(Childless, Node):
Fred Drake1f549022000-09-24 05:21:58 +0000933 nodeType = Node.PROCESSING_INSTRUCTION_NODE
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000934
Fred Drake1f549022000-09-24 05:21:58 +0000935 def __init__(self, target, data):
Fred Drake55c38192000-06-29 19:39:57 +0000936 self.target = self.nodeName = target
937 self.data = self.nodeValue = data
Fred Drake55c38192000-06-29 19:39:57 +0000938
Martin v. Löwis787354c2003-01-25 15:28:29 +0000939 def _get_data(self):
940 return self.data
941 def _set_data(self, value):
942 d = self.__dict__
943 d['data'] = d['nodeValue'] = value
944
945 def _get_target(self):
946 return self.target
947 def _set_target(self, value):
948 d = self.__dict__
949 d['target'] = d['nodeName'] = value
950
951 def __setattr__(self, name, value):
952 if name == "data" or name == "nodeValue":
953 self.__dict__['data'] = self.__dict__['nodeValue'] = value
954 elif name == "target" or name == "nodeName":
955 self.__dict__['target'] = self.__dict__['nodeName'] = value
956 else:
957 self.__dict__[name] = value
958
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000959 def writexml(self, writer, indent="", addindent="", newl=""):
960 writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000961
Martin v. Löwis787354c2003-01-25 15:28:29 +0000962
963class CharacterData(Childless, Node):
964 def _get_length(self):
965 return len(self.data)
966 __len__ = _get_length
967
968 def _get_data(self):
969 return self.__dict__['data']
970 def _set_data(self, data):
971 d = self.__dict__
972 d['data'] = d['nodeValue'] = data
973
974 _get_nodeValue = _get_data
975 _set_nodeValue = _set_data
976
977 def __setattr__(self, name, value):
978 if name == "data" or name == "nodeValue":
979 self.__dict__['data'] = self.__dict__['nodeValue'] = value
980 else:
981 self.__dict__[name] = value
Fred Drake87432f42001-04-04 14:09:46 +0000982
Fred Drake55c38192000-06-29 19:39:57 +0000983 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000984 data = self.data
985 if len(data) > 10:
Fred Drake1f549022000-09-24 05:21:58 +0000986 dotdotdot = "..."
Fred Drake55c38192000-06-29 19:39:57 +0000987 else:
Fred Drake1f549022000-09-24 05:21:58 +0000988 dotdotdot = ""
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000989 return '<DOM %s node "%r%s">' % (
Martin v. Löwis787354c2003-01-25 15:28:29 +0000990 self.__class__.__name__, data[0:10], dotdotdot)
Fred Drake87432f42001-04-04 14:09:46 +0000991
992 def substringData(self, offset, count):
993 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000994 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000995 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000996 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +0000997 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000998 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000999 return self.data[offset:offset+count]
1000
1001 def appendData(self, arg):
1002 self.data = self.data + arg
Fred Drake87432f42001-04-04 14:09:46 +00001003
1004 def insertData(self, offset, arg):
1005 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001006 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001007 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001008 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001009 if arg:
1010 self.data = "%s%s%s" % (
1011 self.data[:offset], arg, self.data[offset:])
Fred Drake87432f42001-04-04 14:09:46 +00001012
1013 def deleteData(self, offset, count):
1014 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001015 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001016 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001017 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001018 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001019 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001020 if count:
1021 self.data = self.data[:offset] + self.data[offset+count:]
Fred Drake87432f42001-04-04 14:09:46 +00001022
1023 def replaceData(self, offset, count, arg):
1024 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001025 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001026 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001027 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001028 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001029 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001030 if count:
1031 self.data = "%s%s%s" % (
1032 self.data[:offset], arg, self.data[offset+count:])
Martin v. Löwis787354c2003-01-25 15:28:29 +00001033
1034defproperty(CharacterData, "length", doc="Length of the string data.")
1035
Fred Drake87432f42001-04-04 14:09:46 +00001036
1037class Text(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001038 # Make sure we don't add an instance __dict__ if we don't already
1039 # have one, at least when that's possible:
Martin v. Löwis995359c2003-01-26 08:59:32 +00001040 # XXX this does not work, CharacterData is an old-style class
1041 # __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001042
Fred Drake87432f42001-04-04 14:09:46 +00001043 nodeType = Node.TEXT_NODE
1044 nodeName = "#text"
1045 attributes = None
Fred Drake55c38192000-06-29 19:39:57 +00001046
Fred Drakef7cf40d2000-12-14 18:16:11 +00001047 def splitText(self, offset):
1048 if offset < 0 or offset > len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001049 raise xml.dom.IndexSizeErr("illegal offset value")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001050 newText = self.__class__()
1051 newText.data = self.data[offset:]
1052 newText.ownerDocument = self.ownerDocument
Fred Drakef7cf40d2000-12-14 18:16:11 +00001053 next = self.nextSibling
1054 if self.parentNode and self in self.parentNode.childNodes:
1055 if next is None:
1056 self.parentNode.appendChild(newText)
1057 else:
1058 self.parentNode.insertBefore(newText, next)
1059 self.data = self.data[:offset]
1060 return newText
1061
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001062 def writexml(self, writer, indent="", addindent="", newl=""):
1063 _write_data(writer, "%s%s%s"%(indent, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001064
Martin v. Löwis787354c2003-01-25 15:28:29 +00001065 # DOM Level 3 (WD 9 April 2002)
1066
1067 def _get_wholeText(self):
1068 L = [self.data]
1069 n = self.previousSibling
1070 while n is not None:
1071 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1072 L.insert(0, n.data)
1073 n = n.previousSibling
1074 else:
1075 break
1076 n = self.nextSibling
1077 while n is not None:
1078 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1079 L.append(n.data)
1080 n = n.nextSibling
1081 else:
1082 break
1083 return ''.join(L)
1084
1085 def replaceWholeText(self, content):
1086 # XXX This needs to be seriously changed if minidom ever
1087 # supports EntityReference nodes.
1088 parent = self.parentNode
1089 n = self.previousSibling
1090 while n is not None:
1091 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1092 next = n.previousSibling
1093 parent.removeChild(n)
1094 n = next
1095 else:
1096 break
1097 n = self.nextSibling
1098 if not content:
1099 parent.removeChild(self)
1100 while n is not None:
1101 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1102 next = n.nextSibling
1103 parent.removeChild(n)
1104 n = next
1105 else:
1106 break
1107 if content:
1108 d = self.__dict__
1109 d['data'] = content
1110 d['nodeValue'] = content
1111 return self
1112 else:
1113 return None
1114
1115 def _get_isWhitespaceInElementContent(self):
1116 if self.data.strip():
1117 return False
1118 elem = _get_containing_element(self)
1119 if elem is None:
1120 return False
1121 info = self.ownerDocument._get_elem_info(elem)
1122 if info is None:
1123 return False
1124 else:
1125 return info.isElementContent()
1126
1127defproperty(Text, "isWhitespaceInElementContent",
1128 doc="True iff this text node contains only whitespace"
1129 " and is in element content.")
1130defproperty(Text, "wholeText",
1131 doc="The text of all logically-adjacent text nodes.")
1132
1133
1134def _get_containing_element(node):
1135 c = node.parentNode
1136 while c is not None:
1137 if c.nodeType == Node.ELEMENT_NODE:
1138 return c
1139 c = c.parentNode
1140 return None
1141
1142def _get_containing_entref(node):
1143 c = node.parentNode
1144 while c is not None:
1145 if c.nodeType == Node.ENTITY_REFERENCE_NODE:
1146 return c
1147 c = c.parentNode
1148 return None
1149
1150
Alex Martelli0ee43512006-08-21 19:53:20 +00001151class Comment(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001152 nodeType = Node.COMMENT_NODE
1153 nodeName = "#comment"
1154
1155 def __init__(self, data):
1156 self.data = self.nodeValue = data
1157
1158 def writexml(self, writer, indent="", addindent="", newl=""):
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001159 if "--" in self.data:
1160 raise ValueError("'--' is not allowed in a comment node")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001161 writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1162
Fred Drake87432f42001-04-04 14:09:46 +00001163
1164class CDATASection(Text):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001165 # Make sure we don't add an instance __dict__ if we don't already
1166 # have one, at least when that's possible:
Martin v. Löwis995359c2003-01-26 08:59:32 +00001167 # XXX this does not work, Text is an old-style class
1168 # __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001169
Fred Drake87432f42001-04-04 14:09:46 +00001170 nodeType = Node.CDATA_SECTION_NODE
1171 nodeName = "#cdata-section"
1172
1173 def writexml(self, writer, indent="", addindent="", newl=""):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001174 if self.data.find("]]>") >= 0:
1175 raise ValueError("']]>' not allowed in a CDATA section")
Guido van Rossum5b5e0b92001-09-19 13:28:25 +00001176 writer.write("<![CDATA[%s]]>" % self.data)
Fred Drake87432f42001-04-04 14:09:46 +00001177
1178
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001179class ReadOnlySequentialNamedNodeMap(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001180 __slots__ = '_seq',
1181
1182 def __init__(self, seq=()):
1183 # seq should be a list or tuple
1184 self._seq = seq
1185
1186 def __len__(self):
1187 return len(self._seq)
1188
1189 def _get_length(self):
1190 return len(self._seq)
1191
1192 def getNamedItem(self, name):
1193 for n in self._seq:
1194 if n.nodeName == name:
1195 return n
1196
1197 def getNamedItemNS(self, namespaceURI, localName):
1198 for n in self._seq:
1199 if n.namespaceURI == namespaceURI and n.localName == localName:
1200 return n
1201
1202 def __getitem__(self, name_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001203 if isinstance(name_or_tuple, tuple):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001204 node = self.getNamedItemNS(*name_or_tuple)
1205 else:
1206 node = self.getNamedItem(name_or_tuple)
1207 if node is None:
Collin Winter70e79802007-08-24 18:57:22 +00001208 raise KeyError(name_or_tuple)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001209 return node
1210
1211 def item(self, index):
1212 if index < 0:
1213 return None
1214 try:
1215 return self._seq[index]
1216 except IndexError:
1217 return None
1218
1219 def removeNamedItem(self, name):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001220 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001221 "NamedNodeMap instance is read-only")
1222
1223 def removeNamedItemNS(self, namespaceURI, localName):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001224 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001225 "NamedNodeMap instance is read-only")
1226
1227 def setNamedItem(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001228 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001229 "NamedNodeMap instance is read-only")
1230
1231 def setNamedItemNS(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001232 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001233 "NamedNodeMap instance is read-only")
1234
1235 def __getstate__(self):
1236 return [self._seq]
1237
1238 def __setstate__(self, state):
1239 self._seq = state[0]
1240
1241defproperty(ReadOnlySequentialNamedNodeMap, "length",
1242 doc="Number of entries in the NamedNodeMap.")
Paul Prescod73678da2000-07-01 04:58:47 +00001243
Fred Drakef7cf40d2000-12-14 18:16:11 +00001244
Martin v. Löwis787354c2003-01-25 15:28:29 +00001245class Identified:
1246 """Mix-in class that supports the publicId and systemId attributes."""
1247
Martin v. Löwis995359c2003-01-26 08:59:32 +00001248 # XXX this does not work, this is an old-style class
1249 # __slots__ = 'publicId', 'systemId'
Martin v. Löwis787354c2003-01-25 15:28:29 +00001250
1251 def _identified_mixin_init(self, publicId, systemId):
1252 self.publicId = publicId
1253 self.systemId = systemId
1254
1255 def _get_publicId(self):
1256 return self.publicId
1257
1258 def _get_systemId(self):
1259 return self.systemId
1260
1261class DocumentType(Identified, Childless, Node):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001262 nodeType = Node.DOCUMENT_TYPE_NODE
1263 nodeValue = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001264 name = None
1265 publicId = None
1266 systemId = None
Fred Drakedc806702001-04-05 14:41:30 +00001267 internalSubset = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001268
1269 def __init__(self, qualifiedName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001270 self.entities = ReadOnlySequentialNamedNodeMap()
1271 self.notations = ReadOnlySequentialNamedNodeMap()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001272 if qualifiedName:
1273 prefix, localname = _nssplit(qualifiedName)
1274 self.name = localname
Martin v. Löwis787354c2003-01-25 15:28:29 +00001275 self.nodeName = self.name
1276
1277 def _get_internalSubset(self):
1278 return self.internalSubset
1279
1280 def cloneNode(self, deep):
1281 if self.ownerDocument is None:
1282 # it's ok
1283 clone = DocumentType(None)
1284 clone.name = self.name
1285 clone.nodeName = self.name
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001286 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001287 if deep:
1288 clone.entities._seq = []
1289 clone.notations._seq = []
1290 for n in self.notations._seq:
1291 notation = Notation(n.nodeName, n.publicId, n.systemId)
1292 clone.notations._seq.append(notation)
1293 n._call_user_data_handler(operation, n, notation)
1294 for e in self.entities._seq:
1295 entity = Entity(e.nodeName, e.publicId, e.systemId,
1296 e.notationName)
1297 entity.actualEncoding = e.actualEncoding
1298 entity.encoding = e.encoding
1299 entity.version = e.version
1300 clone.entities._seq.append(entity)
1301 e._call_user_data_handler(operation, n, entity)
1302 self._call_user_data_handler(operation, self, clone)
1303 return clone
1304 else:
1305 return None
1306
1307 def writexml(self, writer, indent="", addindent="", newl=""):
1308 writer.write("<!DOCTYPE ")
1309 writer.write(self.name)
1310 if self.publicId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001311 writer.write("%s PUBLIC '%s'%s '%s'"
1312 % (newl, self.publicId, newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001313 elif self.systemId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001314 writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001315 if self.internalSubset is not None:
1316 writer.write(" [")
1317 writer.write(self.internalSubset)
1318 writer.write("]")
Georg Brandl175a7dc2005-08-25 22:02:43 +00001319 writer.write(">"+newl)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001320
1321class Entity(Identified, Node):
1322 attributes = None
1323 nodeType = Node.ENTITY_NODE
1324 nodeValue = None
1325
1326 actualEncoding = None
1327 encoding = None
1328 version = None
1329
1330 def __init__(self, name, publicId, systemId, notation):
1331 self.nodeName = name
1332 self.notationName = notation
1333 self.childNodes = NodeList()
1334 self._identified_mixin_init(publicId, systemId)
1335
1336 def _get_actualEncoding(self):
1337 return self.actualEncoding
1338
1339 def _get_encoding(self):
1340 return self.encoding
1341
1342 def _get_version(self):
1343 return self.version
1344
1345 def appendChild(self, newChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001346 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001347 "cannot append children to an entity node")
1348
1349 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001350 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001351 "cannot insert children below an entity node")
1352
1353 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001354 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001355 "cannot remove children from an entity node")
1356
1357 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001358 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001359 "cannot replace children of an entity node")
1360
1361class Notation(Identified, Childless, Node):
1362 nodeType = Node.NOTATION_NODE
1363 nodeValue = None
1364
1365 def __init__(self, name, publicId, systemId):
1366 self.nodeName = name
1367 self._identified_mixin_init(publicId, systemId)
Fred Drakef7cf40d2000-12-14 18:16:11 +00001368
1369
Martin v. Löwis787354c2003-01-25 15:28:29 +00001370class DOMImplementation(DOMImplementationLS):
1371 _features = [("core", "1.0"),
1372 ("core", "2.0"),
1373 ("core", "3.0"),
1374 ("core", None),
1375 ("xml", "1.0"),
1376 ("xml", "2.0"),
1377 ("xml", "3.0"),
1378 ("xml", None),
1379 ("ls-load", "3.0"),
1380 ("ls-load", None),
1381 ]
1382
Fred Drakef7cf40d2000-12-14 18:16:11 +00001383 def hasFeature(self, feature, version):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001384 if version == "":
1385 version = None
1386 return (feature.lower(), version) in self._features
Fred Drakef7cf40d2000-12-14 18:16:11 +00001387
1388 def createDocument(self, namespaceURI, qualifiedName, doctype):
1389 if doctype and doctype.parentNode is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001390 raise xml.dom.WrongDocumentErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001391 "doctype object owned by another DOM tree")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001392 doc = self._create_document()
1393
1394 add_root_element = not (namespaceURI is None
1395 and qualifiedName is None
1396 and doctype is None)
1397
1398 if not qualifiedName and add_root_element:
Martin v. Löwisb417be22001-02-06 01:16:06 +00001399 # The spec is unclear what to raise here; SyntaxErr
1400 # would be the other obvious candidate. Since Xerces raises
1401 # InvalidCharacterErr, and since SyntaxErr is not listed
1402 # for createDocument, that seems to be the better choice.
1403 # XXX: need to check for illegal characters here and in
1404 # createElement.
Martin v. Löwis787354c2003-01-25 15:28:29 +00001405
1406 # DOM Level III clears this up when talking about the return value
1407 # of this function. If namespaceURI, qName and DocType are
1408 # Null the document is returned without a document element
1409 # Otherwise if doctype or namespaceURI are not None
1410 # Then we go back to the above problem
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001411 raise xml.dom.InvalidCharacterErr("Element with no name")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001412
1413 if add_root_element:
1414 prefix, localname = _nssplit(qualifiedName)
1415 if prefix == "xml" \
1416 and namespaceURI != "http://www.w3.org/XML/1998/namespace":
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001417 raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001418 if prefix and not namespaceURI:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001419 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001420 "illegal use of prefix without namespaces")
1421 element = doc.createElementNS(namespaceURI, qualifiedName)
1422 if doctype:
1423 doc.appendChild(doctype)
1424 doc.appendChild(element)
1425
1426 if doctype:
1427 doctype.parentNode = doctype.ownerDocument = doc
1428
Fred Drakef7cf40d2000-12-14 18:16:11 +00001429 doc.doctype = doctype
1430 doc.implementation = self
1431 return doc
1432
1433 def createDocumentType(self, qualifiedName, publicId, systemId):
1434 doctype = DocumentType(qualifiedName)
1435 doctype.publicId = publicId
1436 doctype.systemId = systemId
1437 return doctype
1438
Martin v. Löwis787354c2003-01-25 15:28:29 +00001439 # DOM Level 3 (WD 9 April 2002)
1440
1441 def getInterface(self, feature):
1442 if self.hasFeature(feature, None):
1443 return self
1444 else:
1445 return None
1446
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001447 # internal
Martin v. Löwis787354c2003-01-25 15:28:29 +00001448 def _create_document(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001449 return Document()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001450
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001451class ElementInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001452 """Object that represents content-model information for an element.
1453
1454 This implementation is not expected to be used in practice; DOM
1455 builders should provide implementations which do the right thing
1456 using information available to it.
1457
1458 """
1459
1460 __slots__ = 'tagName',
1461
1462 def __init__(self, name):
1463 self.tagName = name
1464
1465 def getAttributeType(self, aname):
1466 return _no_type
1467
1468 def getAttributeTypeNS(self, namespaceURI, localName):
1469 return _no_type
1470
1471 def isElementContent(self):
1472 return False
1473
1474 def isEmpty(self):
1475 """Returns true iff this element is declared to have an EMPTY
1476 content model."""
1477 return False
1478
1479 def isId(self, aname):
1480 """Returns true iff the named attribte is a DTD-style ID."""
1481 return False
1482
1483 def isIdNS(self, namespaceURI, localName):
1484 """Returns true iff the identified attribute is a DTD-style ID."""
1485 return False
1486
1487 def __getstate__(self):
1488 return self.tagName
1489
1490 def __setstate__(self, state):
1491 self.tagName = state
1492
1493def _clear_id_cache(node):
1494 if node.nodeType == Node.DOCUMENT_NODE:
1495 node._id_cache.clear()
1496 node._id_search_stack = None
1497 elif _in_document(node):
1498 node.ownerDocument._id_cache.clear()
1499 node.ownerDocument._id_search_stack= None
1500
1501class Document(Node, DocumentLS):
1502 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
1503 Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE)
1504
Fred Drake1f549022000-09-24 05:21:58 +00001505 nodeType = Node.DOCUMENT_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +00001506 nodeName = "#document"
1507 nodeValue = None
1508 attributes = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001509 doctype = None
1510 parentNode = None
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001511 previousSibling = nextSibling = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001512
1513 implementation = DOMImplementation()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001514
1515 # Document attributes from Level 3 (WD 9 April 2002)
1516
1517 actualEncoding = None
1518 encoding = None
1519 standalone = None
1520 version = None
1521 strictErrorChecking = False
1522 errorHandler = None
1523 documentURI = None
1524
1525 _magic_id_count = 0
1526
1527 def __init__(self):
1528 self.childNodes = NodeList()
1529 # mapping of (namespaceURI, localName) -> ElementInfo
1530 # and tagName -> ElementInfo
1531 self._elem_info = {}
1532 self._id_cache = {}
1533 self._id_search_stack = None
1534
1535 def _get_elem_info(self, element):
1536 if element.namespaceURI:
1537 key = element.namespaceURI, element.localName
1538 else:
1539 key = element.tagName
1540 return self._elem_info.get(key)
1541
1542 def _get_actualEncoding(self):
1543 return self.actualEncoding
1544
1545 def _get_doctype(self):
1546 return self.doctype
1547
1548 def _get_documentURI(self):
1549 return self.documentURI
1550
1551 def _get_encoding(self):
1552 return self.encoding
1553
1554 def _get_errorHandler(self):
1555 return self.errorHandler
1556
1557 def _get_standalone(self):
1558 return self.standalone
1559
1560 def _get_strictErrorChecking(self):
1561 return self.strictErrorChecking
1562
1563 def _get_version(self):
1564 return self.version
Fred Drake55c38192000-06-29 19:39:57 +00001565
Fred Drake1f549022000-09-24 05:21:58 +00001566 def appendChild(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001567 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001568 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001569 "%s cannot be child of %s" % (repr(node), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001570 if node.parentNode is not None:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001571 # This needs to be done before the next test since this
1572 # may *be* the document element, in which case it should
1573 # end up re-ordered to the end.
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001574 node.parentNode.removeChild(node)
1575
Fred Drakef7cf40d2000-12-14 18:16:11 +00001576 if node.nodeType == Node.ELEMENT_NODE \
1577 and self._get_documentElement():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001578 raise xml.dom.HierarchyRequestErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001579 "two document elements disallowed")
Fred Drake4ccf4a12000-11-21 22:02:22 +00001580 return Node.appendChild(self, node)
Paul Prescod73678da2000-07-01 04:58:47 +00001581
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001582 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001583 try:
1584 self.childNodes.remove(oldChild)
1585 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001586 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001587 oldChild.nextSibling = oldChild.previousSibling = None
1588 oldChild.parentNode = None
1589 if self.documentElement is oldChild:
1590 self.documentElement = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +00001591
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001592 return oldChild
1593
Fred Drakef7cf40d2000-12-14 18:16:11 +00001594 def _get_documentElement(self):
1595 for node in self.childNodes:
1596 if node.nodeType == Node.ELEMENT_NODE:
1597 return node
1598
1599 def unlink(self):
1600 if self.doctype is not None:
1601 self.doctype.unlink()
1602 self.doctype = None
1603 Node.unlink(self)
1604
Martin v. Löwis787354c2003-01-25 15:28:29 +00001605 def cloneNode(self, deep):
1606 if not deep:
1607 return None
1608 clone = self.implementation.createDocument(None, None, None)
1609 clone.encoding = self.encoding
1610 clone.standalone = self.standalone
1611 clone.version = self.version
1612 for n in self.childNodes:
1613 childclone = _clone_node(n, deep, clone)
1614 assert childclone.ownerDocument.isSameNode(clone)
1615 clone.childNodes.append(childclone)
1616 if childclone.nodeType == Node.DOCUMENT_NODE:
1617 assert clone.documentElement is None
1618 elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE:
1619 assert clone.doctype is None
1620 clone.doctype = childclone
1621 childclone.parentNode = clone
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001622 self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED,
Martin v. Löwis787354c2003-01-25 15:28:29 +00001623 self, clone)
1624 return clone
1625
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001626 def createDocumentFragment(self):
1627 d = DocumentFragment()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001628 d.ownerDocument = self
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001629 return d
Fred Drake55c38192000-06-29 19:39:57 +00001630
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001631 def createElement(self, tagName):
1632 e = Element(tagName)
1633 e.ownerDocument = self
1634 return e
Fred Drake55c38192000-06-29 19:39:57 +00001635
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001636 def createTextNode(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001637 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001638 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001639 t = Text()
1640 t.data = data
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001641 t.ownerDocument = self
1642 return t
Fred Drake55c38192000-06-29 19:39:57 +00001643
Fred Drake87432f42001-04-04 14:09:46 +00001644 def createCDATASection(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001645 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001646 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001647 c = CDATASection()
1648 c.data = data
Fred Drake87432f42001-04-04 14:09:46 +00001649 c.ownerDocument = self
1650 return c
1651
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001652 def createComment(self, data):
1653 c = Comment(data)
1654 c.ownerDocument = self
1655 return c
Fred Drake55c38192000-06-29 19:39:57 +00001656
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001657 def createProcessingInstruction(self, target, data):
1658 p = ProcessingInstruction(target, data)
1659 p.ownerDocument = self
1660 return p
1661
1662 def createAttribute(self, qName):
1663 a = Attr(qName)
1664 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001665 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001666 return a
Fred Drake55c38192000-06-29 19:39:57 +00001667
1668 def createElementNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001669 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001670 e = Element(qualifiedName, namespaceURI, prefix)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001671 e.ownerDocument = self
1672 return e
Fred Drake55c38192000-06-29 19:39:57 +00001673
1674 def createAttributeNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001675 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001676 a = Attr(qualifiedName, namespaceURI, localName, prefix)
1677 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001678 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001679 return a
Fred Drake55c38192000-06-29 19:39:57 +00001680
Martin v. Löwis787354c2003-01-25 15:28:29 +00001681 # A couple of implementation-specific helpers to create node types
1682 # not supported by the W3C DOM specs:
1683
1684 def _create_entity(self, name, publicId, systemId, notationName):
1685 e = Entity(name, publicId, systemId, notationName)
1686 e.ownerDocument = self
1687 return e
1688
1689 def _create_notation(self, name, publicId, systemId):
1690 n = Notation(name, publicId, systemId)
1691 n.ownerDocument = self
1692 return n
1693
1694 def getElementById(self, id):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +00001695 if id in self._id_cache:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001696 return self._id_cache[id]
1697 if not (self._elem_info or self._magic_id_count):
1698 return None
1699
1700 stack = self._id_search_stack
1701 if stack is None:
1702 # we never searched before, or the cache has been cleared
1703 stack = [self.documentElement]
1704 self._id_search_stack = stack
1705 elif not stack:
1706 # Previous search was completed and cache is still valid;
1707 # no matching node.
1708 return None
1709
1710 result = None
1711 while stack:
1712 node = stack.pop()
1713 # add child elements to stack for continued searching
1714 stack.extend([child for child in node.childNodes
1715 if child.nodeType in _nodeTypes_with_children])
1716 # check this node
1717 info = self._get_elem_info(node)
1718 if info:
1719 # We have to process all ID attributes before
1720 # returning in order to get all the attributes set to
1721 # be IDs using Element.setIdAttribute*().
1722 for attr in node.attributes.values():
1723 if attr.namespaceURI:
1724 if info.isIdNS(attr.namespaceURI, attr.localName):
1725 self._id_cache[attr.value] = node
1726 if attr.value == id:
1727 result = node
1728 elif not node._magic_id_nodes:
1729 break
1730 elif info.isId(attr.name):
1731 self._id_cache[attr.value] = node
1732 if attr.value == id:
1733 result = node
1734 elif not node._magic_id_nodes:
1735 break
1736 elif attr._is_id:
1737 self._id_cache[attr.value] = node
1738 if attr.value == id:
1739 result = node
1740 elif node._magic_id_nodes == 1:
1741 break
1742 elif node._magic_id_nodes:
1743 for attr in node.attributes.values():
1744 if attr._is_id:
1745 self._id_cache[attr.value] = node
1746 if attr.value == id:
1747 result = node
1748 if result is not None:
1749 break
1750 return result
1751
Fred Drake1f549022000-09-24 05:21:58 +00001752 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001753 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drakefbe7b4f2001-07-04 06:25:53 +00001754
1755 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001756 return _get_elements_by_tagName_ns_helper(
1757 self, namespaceURI, localName, NodeList())
1758
1759 def isSupported(self, feature, version):
1760 return self.implementation.hasFeature(feature, version)
1761
1762 def importNode(self, node, deep):
1763 if node.nodeType == Node.DOCUMENT_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001764 raise xml.dom.NotSupportedErr("cannot import document nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001765 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001766 raise xml.dom.NotSupportedErr("cannot import document type nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001767 return _clone_node(node, deep, self)
Fred Drake55c38192000-06-29 19:39:57 +00001768
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001769 def writexml(self, writer, indent="", addindent="", newl="",
1770 encoding = None):
1771 if encoding is None:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001772 writer.write('<?xml version="1.0" ?>'+newl)
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001773 else:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001774 writer.write('<?xml version="1.0" encoding="%s"?>%s' % (encoding, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001775 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001776 node.writexml(writer, indent, addindent, newl)
Fred Drake55c38192000-06-29 19:39:57 +00001777
Martin v. Löwis787354c2003-01-25 15:28:29 +00001778 # DOM Level 3 (WD 9 April 2002)
1779
1780 def renameNode(self, n, namespaceURI, name):
1781 if n.ownerDocument is not self:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001782 raise xml.dom.WrongDocumentErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001783 "cannot rename nodes from other documents;\n"
1784 "expected %s,\nfound %s" % (self, n.ownerDocument))
1785 if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001786 raise xml.dom.NotSupportedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001787 "renameNode() only applies to element and attribute nodes")
1788 if namespaceURI != EMPTY_NAMESPACE:
1789 if ':' in name:
1790 prefix, localName = name.split(':', 1)
1791 if ( prefix == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001792 and namespaceURI != xml.dom.XMLNS_NAMESPACE):
1793 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001794 "illegal use of 'xmlns' prefix")
1795 else:
1796 if ( name == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001797 and namespaceURI != xml.dom.XMLNS_NAMESPACE
Martin v. Löwis787354c2003-01-25 15:28:29 +00001798 and n.nodeType == Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001799 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001800 "illegal use of the 'xmlns' attribute")
1801 prefix = None
1802 localName = name
1803 else:
1804 prefix = None
1805 localName = None
1806 if n.nodeType == Node.ATTRIBUTE_NODE:
1807 element = n.ownerElement
1808 if element is not None:
1809 is_id = n._is_id
1810 element.removeAttributeNode(n)
1811 else:
1812 element = None
1813 # avoid __setattr__
1814 d = n.__dict__
1815 d['prefix'] = prefix
1816 d['localName'] = localName
1817 d['namespaceURI'] = namespaceURI
1818 d['nodeName'] = name
1819 if n.nodeType == Node.ELEMENT_NODE:
1820 d['tagName'] = name
1821 else:
1822 # attribute node
1823 d['name'] = name
1824 if element is not None:
1825 element.setAttributeNode(n)
1826 if is_id:
1827 element.setIdAttributeNode(n)
1828 # It's not clear from a semantic perspective whether we should
1829 # call the user data handlers for the NODE_RENAMED event since
1830 # we're re-using the existing node. The draft spec has been
1831 # interpreted as meaning "no, don't call the handler unless a
1832 # new node is created."
1833 return n
1834
1835defproperty(Document, "documentElement",
1836 doc="Top-level element of this document.")
1837
1838
1839def _clone_node(node, deep, newOwnerDocument):
1840 """
1841 Clone a node and give it the new owner document.
1842 Called by Node.cloneNode and Document.importNode
1843 """
1844 if node.ownerDocument.isSameNode(newOwnerDocument):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001845 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001846 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001847 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001848 if node.nodeType == Node.ELEMENT_NODE:
1849 clone = newOwnerDocument.createElementNS(node.namespaceURI,
1850 node.nodeName)
1851 for attr in node.attributes.values():
1852 clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
1853 a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)
1854 a.specified = attr.specified
1855
1856 if deep:
1857 for child in node.childNodes:
1858 c = _clone_node(child, deep, newOwnerDocument)
1859 clone.appendChild(c)
1860
1861 elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
1862 clone = newOwnerDocument.createDocumentFragment()
1863 if deep:
1864 for child in node.childNodes:
1865 c = _clone_node(child, deep, newOwnerDocument)
1866 clone.appendChild(c)
1867
1868 elif node.nodeType == Node.TEXT_NODE:
1869 clone = newOwnerDocument.createTextNode(node.data)
1870 elif node.nodeType == Node.CDATA_SECTION_NODE:
1871 clone = newOwnerDocument.createCDATASection(node.data)
1872 elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
1873 clone = newOwnerDocument.createProcessingInstruction(node.target,
1874 node.data)
1875 elif node.nodeType == Node.COMMENT_NODE:
1876 clone = newOwnerDocument.createComment(node.data)
1877 elif node.nodeType == Node.ATTRIBUTE_NODE:
1878 clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
1879 node.nodeName)
1880 clone.specified = True
1881 clone.value = node.value
1882 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
1883 assert node.ownerDocument is not newOwnerDocument
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001884 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001885 clone = newOwnerDocument.implementation.createDocumentType(
1886 node.name, node.publicId, node.systemId)
1887 clone.ownerDocument = newOwnerDocument
1888 if deep:
1889 clone.entities._seq = []
1890 clone.notations._seq = []
1891 for n in node.notations._seq:
1892 notation = Notation(n.nodeName, n.publicId, n.systemId)
1893 notation.ownerDocument = newOwnerDocument
1894 clone.notations._seq.append(notation)
1895 if hasattr(n, '_call_user_data_handler'):
1896 n._call_user_data_handler(operation, n, notation)
1897 for e in node.entities._seq:
1898 entity = Entity(e.nodeName, e.publicId, e.systemId,
1899 e.notationName)
1900 entity.actualEncoding = e.actualEncoding
1901 entity.encoding = e.encoding
1902 entity.version = e.version
1903 entity.ownerDocument = newOwnerDocument
1904 clone.entities._seq.append(entity)
1905 if hasattr(e, '_call_user_data_handler'):
1906 e._call_user_data_handler(operation, n, entity)
1907 else:
1908 # Note the cloning of Document and DocumentType nodes is
1909 # implemenetation specific. minidom handles those cases
1910 # directly in the cloneNode() methods.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001911 raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001912
1913 # Check for _call_user_data_handler() since this could conceivably
1914 # used with other DOM implementations (one of the FourThought
1915 # DOMs, perhaps?).
1916 if hasattr(node, '_call_user_data_handler'):
1917 node._call_user_data_handler(operation, node, clone)
1918 return clone
1919
1920
1921def _nssplit(qualifiedName):
1922 fields = qualifiedName.split(':', 1)
1923 if len(fields) == 2:
1924 return fields
1925 else:
1926 return (None, fields[0])
1927
1928
Martin v. Löwis787354c2003-01-25 15:28:29 +00001929def _do_pulldom_parse(func, args, kwargs):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001930 events = func(*args, **kwargs)
Fred Drake1f549022000-09-24 05:21:58 +00001931 toktype, rootNode = events.getEvent()
1932 events.expandNode(rootNode)
Martin v. Löwisb417be22001-02-06 01:16:06 +00001933 events.clear()
Fred Drake55c38192000-06-29 19:39:57 +00001934 return rootNode
1935
Martin v. Löwis787354c2003-01-25 15:28:29 +00001936def parse(file, parser=None, bufsize=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001937 """Parse a file into a DOM by filename or file object."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001938 if parser is None and not bufsize:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001939 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001940 return expatbuilder.parse(file)
1941 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001942 from xml.dom import pulldom
Raymond Hettingerff41c482003-04-06 09:01:11 +00001943 return _do_pulldom_parse(pulldom.parse, (file,),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001944 {'parser': parser, 'bufsize': bufsize})
Fred Drake55c38192000-06-29 19:39:57 +00001945
Martin v. Löwis787354c2003-01-25 15:28:29 +00001946def parseString(string, parser=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001947 """Parse a file into a DOM from a string."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001948 if parser is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001949 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001950 return expatbuilder.parseString(string)
1951 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001952 from xml.dom import pulldom
Martin v. Löwis787354c2003-01-25 15:28:29 +00001953 return _do_pulldom_parse(pulldom.parseString, (string,),
1954 {'parser': parser})
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001955
Martin v. Löwis787354c2003-01-25 15:28:29 +00001956def getDOMImplementation(features=None):
1957 if features:
Christian Heimesc9543e42007-11-28 08:28:28 +00001958 if isinstance(features, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001959 features = domreg._parse_feature_string(features)
1960 for f, v in features:
1961 if not Document.implementation.hasFeature(f, v):
1962 return None
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001963 return Document.implementation