blob: 7616b46fe0e98a1bf62884a0da459dd394011b24 [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
923 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000924 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000925 self.nodeName + " nodes do not have children")
926
927
928class ProcessingInstruction(Childless, Node):
Fred Drake1f549022000-09-24 05:21:58 +0000929 nodeType = Node.PROCESSING_INSTRUCTION_NODE
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000930
Fred Drake1f549022000-09-24 05:21:58 +0000931 def __init__(self, target, data):
Fred Drake55c38192000-06-29 19:39:57 +0000932 self.target = self.nodeName = target
933 self.data = self.nodeValue = data
Fred Drake55c38192000-06-29 19:39:57 +0000934
Martin v. Löwis787354c2003-01-25 15:28:29 +0000935 def _get_data(self):
936 return self.data
937 def _set_data(self, value):
938 d = self.__dict__
939 d['data'] = d['nodeValue'] = value
940
941 def _get_target(self):
942 return self.target
943 def _set_target(self, value):
944 d = self.__dict__
945 d['target'] = d['nodeName'] = value
946
947 def __setattr__(self, name, value):
948 if name == "data" or name == "nodeValue":
949 self.__dict__['data'] = self.__dict__['nodeValue'] = value
950 elif name == "target" or name == "nodeName":
951 self.__dict__['target'] = self.__dict__['nodeName'] = value
952 else:
953 self.__dict__[name] = value
954
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000955 def writexml(self, writer, indent="", addindent="", newl=""):
956 writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000957
Martin v. Löwis787354c2003-01-25 15:28:29 +0000958
959class CharacterData(Childless, Node):
960 def _get_length(self):
961 return len(self.data)
962 __len__ = _get_length
963
964 def _get_data(self):
965 return self.__dict__['data']
966 def _set_data(self, data):
967 d = self.__dict__
968 d['data'] = d['nodeValue'] = data
969
970 _get_nodeValue = _get_data
971 _set_nodeValue = _set_data
972
973 def __setattr__(self, name, value):
974 if name == "data" or name == "nodeValue":
975 self.__dict__['data'] = self.__dict__['nodeValue'] = value
976 else:
977 self.__dict__[name] = value
Fred Drake87432f42001-04-04 14:09:46 +0000978
Fred Drake55c38192000-06-29 19:39:57 +0000979 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000980 data = self.data
981 if len(data) > 10:
Fred Drake1f549022000-09-24 05:21:58 +0000982 dotdotdot = "..."
Fred Drake55c38192000-06-29 19:39:57 +0000983 else:
Fred Drake1f549022000-09-24 05:21:58 +0000984 dotdotdot = ""
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000985 return '<DOM %s node "%r%s">' % (
Martin v. Löwis787354c2003-01-25 15:28:29 +0000986 self.__class__.__name__, data[0:10], dotdotdot)
Fred Drake87432f42001-04-04 14:09:46 +0000987
988 def substringData(self, offset, count):
989 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000990 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000991 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000992 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +0000993 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000994 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000995 return self.data[offset:offset+count]
996
997 def appendData(self, arg):
998 self.data = self.data + arg
Fred Drake87432f42001-04-04 14:09:46 +0000999
1000 def insertData(self, offset, 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 arg:
1006 self.data = "%s%s%s" % (
1007 self.data[:offset], arg, self.data[offset:])
Fred Drake87432f42001-04-04 14:09:46 +00001008
1009 def deleteData(self, offset, count):
1010 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001011 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001012 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001013 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001014 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001015 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001016 if count:
1017 self.data = self.data[:offset] + self.data[offset+count:]
Fred Drake87432f42001-04-04 14:09:46 +00001018
1019 def replaceData(self, offset, count, arg):
1020 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001021 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001022 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001023 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001024 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001025 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001026 if count:
1027 self.data = "%s%s%s" % (
1028 self.data[:offset], arg, self.data[offset+count:])
Martin v. Löwis787354c2003-01-25 15:28:29 +00001029
1030defproperty(CharacterData, "length", doc="Length of the string data.")
1031
Fred Drake87432f42001-04-04 14:09:46 +00001032
1033class Text(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001034 # Make sure we don't add an instance __dict__ if we don't already
1035 # have one, at least when that's possible:
Martin v. Löwis995359c2003-01-26 08:59:32 +00001036 # XXX this does not work, CharacterData is an old-style class
1037 # __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001038
Fred Drake87432f42001-04-04 14:09:46 +00001039 nodeType = Node.TEXT_NODE
1040 nodeName = "#text"
1041 attributes = None
Fred Drake55c38192000-06-29 19:39:57 +00001042
Fred Drakef7cf40d2000-12-14 18:16:11 +00001043 def splitText(self, offset):
1044 if offset < 0 or offset > len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001045 raise xml.dom.IndexSizeErr("illegal offset value")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001046 newText = self.__class__()
1047 newText.data = self.data[offset:]
1048 newText.ownerDocument = self.ownerDocument
Fred Drakef7cf40d2000-12-14 18:16:11 +00001049 next = self.nextSibling
1050 if self.parentNode and self in self.parentNode.childNodes:
1051 if next is None:
1052 self.parentNode.appendChild(newText)
1053 else:
1054 self.parentNode.insertBefore(newText, next)
1055 self.data = self.data[:offset]
1056 return newText
1057
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001058 def writexml(self, writer, indent="", addindent="", newl=""):
1059 _write_data(writer, "%s%s%s"%(indent, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001060
Martin v. Löwis787354c2003-01-25 15:28:29 +00001061 # DOM Level 3 (WD 9 April 2002)
1062
1063 def _get_wholeText(self):
1064 L = [self.data]
1065 n = self.previousSibling
1066 while n is not None:
1067 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1068 L.insert(0, n.data)
1069 n = n.previousSibling
1070 else:
1071 break
1072 n = self.nextSibling
1073 while n is not None:
1074 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1075 L.append(n.data)
1076 n = n.nextSibling
1077 else:
1078 break
1079 return ''.join(L)
1080
1081 def replaceWholeText(self, content):
1082 # XXX This needs to be seriously changed if minidom ever
1083 # supports EntityReference nodes.
1084 parent = self.parentNode
1085 n = self.previousSibling
1086 while n is not None:
1087 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1088 next = n.previousSibling
1089 parent.removeChild(n)
1090 n = next
1091 else:
1092 break
1093 n = self.nextSibling
1094 if not content:
1095 parent.removeChild(self)
1096 while n is not None:
1097 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1098 next = n.nextSibling
1099 parent.removeChild(n)
1100 n = next
1101 else:
1102 break
1103 if content:
1104 d = self.__dict__
1105 d['data'] = content
1106 d['nodeValue'] = content
1107 return self
1108 else:
1109 return None
1110
1111 def _get_isWhitespaceInElementContent(self):
1112 if self.data.strip():
1113 return False
1114 elem = _get_containing_element(self)
1115 if elem is None:
1116 return False
1117 info = self.ownerDocument._get_elem_info(elem)
1118 if info is None:
1119 return False
1120 else:
1121 return info.isElementContent()
1122
1123defproperty(Text, "isWhitespaceInElementContent",
1124 doc="True iff this text node contains only whitespace"
1125 " and is in element content.")
1126defproperty(Text, "wholeText",
1127 doc="The text of all logically-adjacent text nodes.")
1128
1129
1130def _get_containing_element(node):
1131 c = node.parentNode
1132 while c is not None:
1133 if c.nodeType == Node.ELEMENT_NODE:
1134 return c
1135 c = c.parentNode
1136 return None
1137
1138def _get_containing_entref(node):
1139 c = node.parentNode
1140 while c is not None:
1141 if c.nodeType == Node.ENTITY_REFERENCE_NODE:
1142 return c
1143 c = c.parentNode
1144 return None
1145
1146
Alex Martelli0ee43512006-08-21 19:53:20 +00001147class Comment(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001148 nodeType = Node.COMMENT_NODE
1149 nodeName = "#comment"
1150
1151 def __init__(self, data):
1152 self.data = self.nodeValue = data
1153
1154 def writexml(self, writer, indent="", addindent="", newl=""):
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001155 if "--" in self.data:
1156 raise ValueError("'--' is not allowed in a comment node")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001157 writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1158
Fred Drake87432f42001-04-04 14:09:46 +00001159
1160class CDATASection(Text):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001161 # Make sure we don't add an instance __dict__ if we don't already
1162 # have one, at least when that's possible:
Martin v. Löwis995359c2003-01-26 08:59:32 +00001163 # XXX this does not work, Text is an old-style class
1164 # __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001165
Fred Drake87432f42001-04-04 14:09:46 +00001166 nodeType = Node.CDATA_SECTION_NODE
1167 nodeName = "#cdata-section"
1168
1169 def writexml(self, writer, indent="", addindent="", newl=""):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001170 if self.data.find("]]>") >= 0:
1171 raise ValueError("']]>' not allowed in a CDATA section")
Guido van Rossum5b5e0b92001-09-19 13:28:25 +00001172 writer.write("<![CDATA[%s]]>" % self.data)
Fred Drake87432f42001-04-04 14:09:46 +00001173
1174
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001175class ReadOnlySequentialNamedNodeMap(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001176 __slots__ = '_seq',
1177
1178 def __init__(self, seq=()):
1179 # seq should be a list or tuple
1180 self._seq = seq
1181
1182 def __len__(self):
1183 return len(self._seq)
1184
1185 def _get_length(self):
1186 return len(self._seq)
1187
1188 def getNamedItem(self, name):
1189 for n in self._seq:
1190 if n.nodeName == name:
1191 return n
1192
1193 def getNamedItemNS(self, namespaceURI, localName):
1194 for n in self._seq:
1195 if n.namespaceURI == namespaceURI and n.localName == localName:
1196 return n
1197
1198 def __getitem__(self, name_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001199 if isinstance(name_or_tuple, tuple):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001200 node = self.getNamedItemNS(*name_or_tuple)
1201 else:
1202 node = self.getNamedItem(name_or_tuple)
1203 if node is None:
Collin Winter70e79802007-08-24 18:57:22 +00001204 raise KeyError(name_or_tuple)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001205 return node
1206
1207 def item(self, index):
1208 if index < 0:
1209 return None
1210 try:
1211 return self._seq[index]
1212 except IndexError:
1213 return None
1214
1215 def removeNamedItem(self, name):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001216 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001217 "NamedNodeMap instance is read-only")
1218
1219 def removeNamedItemNS(self, namespaceURI, localName):
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 setNamedItem(self, node):
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 setNamedItemNS(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 __getstate__(self):
1232 return [self._seq]
1233
1234 def __setstate__(self, state):
1235 self._seq = state[0]
1236
1237defproperty(ReadOnlySequentialNamedNodeMap, "length",
1238 doc="Number of entries in the NamedNodeMap.")
Paul Prescod73678da2000-07-01 04:58:47 +00001239
Fred Drakef7cf40d2000-12-14 18:16:11 +00001240
Martin v. Löwis787354c2003-01-25 15:28:29 +00001241class Identified:
1242 """Mix-in class that supports the publicId and systemId attributes."""
1243
Martin v. Löwis995359c2003-01-26 08:59:32 +00001244 # XXX this does not work, this is an old-style class
1245 # __slots__ = 'publicId', 'systemId'
Martin v. Löwis787354c2003-01-25 15:28:29 +00001246
1247 def _identified_mixin_init(self, publicId, systemId):
1248 self.publicId = publicId
1249 self.systemId = systemId
1250
1251 def _get_publicId(self):
1252 return self.publicId
1253
1254 def _get_systemId(self):
1255 return self.systemId
1256
1257class DocumentType(Identified, Childless, Node):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001258 nodeType = Node.DOCUMENT_TYPE_NODE
1259 nodeValue = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001260 name = None
1261 publicId = None
1262 systemId = None
Fred Drakedc806702001-04-05 14:41:30 +00001263 internalSubset = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001264
1265 def __init__(self, qualifiedName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001266 self.entities = ReadOnlySequentialNamedNodeMap()
1267 self.notations = ReadOnlySequentialNamedNodeMap()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001268 if qualifiedName:
1269 prefix, localname = _nssplit(qualifiedName)
1270 self.name = localname
Martin v. Löwis787354c2003-01-25 15:28:29 +00001271 self.nodeName = self.name
1272
1273 def _get_internalSubset(self):
1274 return self.internalSubset
1275
1276 def cloneNode(self, deep):
1277 if self.ownerDocument is None:
1278 # it's ok
1279 clone = DocumentType(None)
1280 clone.name = self.name
1281 clone.nodeName = self.name
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001282 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001283 if deep:
1284 clone.entities._seq = []
1285 clone.notations._seq = []
1286 for n in self.notations._seq:
1287 notation = Notation(n.nodeName, n.publicId, n.systemId)
1288 clone.notations._seq.append(notation)
1289 n._call_user_data_handler(operation, n, notation)
1290 for e in self.entities._seq:
1291 entity = Entity(e.nodeName, e.publicId, e.systemId,
1292 e.notationName)
1293 entity.actualEncoding = e.actualEncoding
1294 entity.encoding = e.encoding
1295 entity.version = e.version
1296 clone.entities._seq.append(entity)
1297 e._call_user_data_handler(operation, n, entity)
1298 self._call_user_data_handler(operation, self, clone)
1299 return clone
1300 else:
1301 return None
1302
1303 def writexml(self, writer, indent="", addindent="", newl=""):
1304 writer.write("<!DOCTYPE ")
1305 writer.write(self.name)
1306 if self.publicId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001307 writer.write("%s PUBLIC '%s'%s '%s'"
1308 % (newl, self.publicId, newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001309 elif self.systemId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001310 writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001311 if self.internalSubset is not None:
1312 writer.write(" [")
1313 writer.write(self.internalSubset)
1314 writer.write("]")
Georg Brandl175a7dc2005-08-25 22:02:43 +00001315 writer.write(">"+newl)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001316
1317class Entity(Identified, Node):
1318 attributes = None
1319 nodeType = Node.ENTITY_NODE
1320 nodeValue = None
1321
1322 actualEncoding = None
1323 encoding = None
1324 version = None
1325
1326 def __init__(self, name, publicId, systemId, notation):
1327 self.nodeName = name
1328 self.notationName = notation
1329 self.childNodes = NodeList()
1330 self._identified_mixin_init(publicId, systemId)
1331
1332 def _get_actualEncoding(self):
1333 return self.actualEncoding
1334
1335 def _get_encoding(self):
1336 return self.encoding
1337
1338 def _get_version(self):
1339 return self.version
1340
1341 def appendChild(self, newChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001342 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001343 "cannot append children to an entity node")
1344
1345 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001346 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001347 "cannot insert children below an entity node")
1348
1349 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001350 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001351 "cannot remove children from an entity node")
1352
1353 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001354 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001355 "cannot replace children of an entity node")
1356
1357class Notation(Identified, Childless, Node):
1358 nodeType = Node.NOTATION_NODE
1359 nodeValue = None
1360
1361 def __init__(self, name, publicId, systemId):
1362 self.nodeName = name
1363 self._identified_mixin_init(publicId, systemId)
Fred Drakef7cf40d2000-12-14 18:16:11 +00001364
1365
Martin v. Löwis787354c2003-01-25 15:28:29 +00001366class DOMImplementation(DOMImplementationLS):
1367 _features = [("core", "1.0"),
1368 ("core", "2.0"),
1369 ("core", "3.0"),
1370 ("core", None),
1371 ("xml", "1.0"),
1372 ("xml", "2.0"),
1373 ("xml", "3.0"),
1374 ("xml", None),
1375 ("ls-load", "3.0"),
1376 ("ls-load", None),
1377 ]
1378
Fred Drakef7cf40d2000-12-14 18:16:11 +00001379 def hasFeature(self, feature, version):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001380 if version == "":
1381 version = None
1382 return (feature.lower(), version) in self._features
Fred Drakef7cf40d2000-12-14 18:16:11 +00001383
1384 def createDocument(self, namespaceURI, qualifiedName, doctype):
1385 if doctype and doctype.parentNode is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001386 raise xml.dom.WrongDocumentErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001387 "doctype object owned by another DOM tree")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001388 doc = self._create_document()
1389
1390 add_root_element = not (namespaceURI is None
1391 and qualifiedName is None
1392 and doctype is None)
1393
1394 if not qualifiedName and add_root_element:
Martin v. Löwisb417be22001-02-06 01:16:06 +00001395 # The spec is unclear what to raise here; SyntaxErr
1396 # would be the other obvious candidate. Since Xerces raises
1397 # InvalidCharacterErr, and since SyntaxErr is not listed
1398 # for createDocument, that seems to be the better choice.
1399 # XXX: need to check for illegal characters here and in
1400 # createElement.
Martin v. Löwis787354c2003-01-25 15:28:29 +00001401
1402 # DOM Level III clears this up when talking about the return value
1403 # of this function. If namespaceURI, qName and DocType are
1404 # Null the document is returned without a document element
1405 # Otherwise if doctype or namespaceURI are not None
1406 # Then we go back to the above problem
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001407 raise xml.dom.InvalidCharacterErr("Element with no name")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001408
1409 if add_root_element:
1410 prefix, localname = _nssplit(qualifiedName)
1411 if prefix == "xml" \
1412 and namespaceURI != "http://www.w3.org/XML/1998/namespace":
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001413 raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001414 if prefix and not namespaceURI:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001415 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001416 "illegal use of prefix without namespaces")
1417 element = doc.createElementNS(namespaceURI, qualifiedName)
1418 if doctype:
1419 doc.appendChild(doctype)
1420 doc.appendChild(element)
1421
1422 if doctype:
1423 doctype.parentNode = doctype.ownerDocument = doc
1424
Fred Drakef7cf40d2000-12-14 18:16:11 +00001425 doc.doctype = doctype
1426 doc.implementation = self
1427 return doc
1428
1429 def createDocumentType(self, qualifiedName, publicId, systemId):
1430 doctype = DocumentType(qualifiedName)
1431 doctype.publicId = publicId
1432 doctype.systemId = systemId
1433 return doctype
1434
Martin v. Löwis787354c2003-01-25 15:28:29 +00001435 # DOM Level 3 (WD 9 April 2002)
1436
1437 def getInterface(self, feature):
1438 if self.hasFeature(feature, None):
1439 return self
1440 else:
1441 return None
1442
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001443 # internal
Martin v. Löwis787354c2003-01-25 15:28:29 +00001444 def _create_document(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001445 return Document()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001446
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001447class ElementInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001448 """Object that represents content-model information for an element.
1449
1450 This implementation is not expected to be used in practice; DOM
1451 builders should provide implementations which do the right thing
1452 using information available to it.
1453
1454 """
1455
1456 __slots__ = 'tagName',
1457
1458 def __init__(self, name):
1459 self.tagName = name
1460
1461 def getAttributeType(self, aname):
1462 return _no_type
1463
1464 def getAttributeTypeNS(self, namespaceURI, localName):
1465 return _no_type
1466
1467 def isElementContent(self):
1468 return False
1469
1470 def isEmpty(self):
1471 """Returns true iff this element is declared to have an EMPTY
1472 content model."""
1473 return False
1474
1475 def isId(self, aname):
1476 """Returns true iff the named attribte is a DTD-style ID."""
1477 return False
1478
1479 def isIdNS(self, namespaceURI, localName):
1480 """Returns true iff the identified attribute is a DTD-style ID."""
1481 return False
1482
1483 def __getstate__(self):
1484 return self.tagName
1485
1486 def __setstate__(self, state):
1487 self.tagName = state
1488
1489def _clear_id_cache(node):
1490 if node.nodeType == Node.DOCUMENT_NODE:
1491 node._id_cache.clear()
1492 node._id_search_stack = None
1493 elif _in_document(node):
1494 node.ownerDocument._id_cache.clear()
1495 node.ownerDocument._id_search_stack= None
1496
1497class Document(Node, DocumentLS):
1498 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
1499 Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE)
1500
Fred Drake1f549022000-09-24 05:21:58 +00001501 nodeType = Node.DOCUMENT_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +00001502 nodeName = "#document"
1503 nodeValue = None
1504 attributes = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001505 doctype = None
1506 parentNode = None
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001507 previousSibling = nextSibling = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001508
1509 implementation = DOMImplementation()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001510
1511 # Document attributes from Level 3 (WD 9 April 2002)
1512
1513 actualEncoding = None
1514 encoding = None
1515 standalone = None
1516 version = None
1517 strictErrorChecking = False
1518 errorHandler = None
1519 documentURI = None
1520
1521 _magic_id_count = 0
1522
1523 def __init__(self):
1524 self.childNodes = NodeList()
1525 # mapping of (namespaceURI, localName) -> ElementInfo
1526 # and tagName -> ElementInfo
1527 self._elem_info = {}
1528 self._id_cache = {}
1529 self._id_search_stack = None
1530
1531 def _get_elem_info(self, element):
1532 if element.namespaceURI:
1533 key = element.namespaceURI, element.localName
1534 else:
1535 key = element.tagName
1536 return self._elem_info.get(key)
1537
1538 def _get_actualEncoding(self):
1539 return self.actualEncoding
1540
1541 def _get_doctype(self):
1542 return self.doctype
1543
1544 def _get_documentURI(self):
1545 return self.documentURI
1546
1547 def _get_encoding(self):
1548 return self.encoding
1549
1550 def _get_errorHandler(self):
1551 return self.errorHandler
1552
1553 def _get_standalone(self):
1554 return self.standalone
1555
1556 def _get_strictErrorChecking(self):
1557 return self.strictErrorChecking
1558
1559 def _get_version(self):
1560 return self.version
Fred Drake55c38192000-06-29 19:39:57 +00001561
Fred Drake1f549022000-09-24 05:21:58 +00001562 def appendChild(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001563 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001564 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001565 "%s cannot be child of %s" % (repr(node), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001566 if node.parentNode is not None:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001567 # This needs to be done before the next test since this
1568 # may *be* the document element, in which case it should
1569 # end up re-ordered to the end.
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001570 node.parentNode.removeChild(node)
1571
Fred Drakef7cf40d2000-12-14 18:16:11 +00001572 if node.nodeType == Node.ELEMENT_NODE \
1573 and self._get_documentElement():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001574 raise xml.dom.HierarchyRequestErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001575 "two document elements disallowed")
Fred Drake4ccf4a12000-11-21 22:02:22 +00001576 return Node.appendChild(self, node)
Paul Prescod73678da2000-07-01 04:58:47 +00001577
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001578 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001579 try:
1580 self.childNodes.remove(oldChild)
1581 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001582 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001583 oldChild.nextSibling = oldChild.previousSibling = None
1584 oldChild.parentNode = None
1585 if self.documentElement is oldChild:
1586 self.documentElement = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +00001587
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001588 return oldChild
1589
Fred Drakef7cf40d2000-12-14 18:16:11 +00001590 def _get_documentElement(self):
1591 for node in self.childNodes:
1592 if node.nodeType == Node.ELEMENT_NODE:
1593 return node
1594
1595 def unlink(self):
1596 if self.doctype is not None:
1597 self.doctype.unlink()
1598 self.doctype = None
1599 Node.unlink(self)
1600
Martin v. Löwis787354c2003-01-25 15:28:29 +00001601 def cloneNode(self, deep):
1602 if not deep:
1603 return None
1604 clone = self.implementation.createDocument(None, None, None)
1605 clone.encoding = self.encoding
1606 clone.standalone = self.standalone
1607 clone.version = self.version
1608 for n in self.childNodes:
1609 childclone = _clone_node(n, deep, clone)
1610 assert childclone.ownerDocument.isSameNode(clone)
1611 clone.childNodes.append(childclone)
1612 if childclone.nodeType == Node.DOCUMENT_NODE:
1613 assert clone.documentElement is None
1614 elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE:
1615 assert clone.doctype is None
1616 clone.doctype = childclone
1617 childclone.parentNode = clone
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001618 self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED,
Martin v. Löwis787354c2003-01-25 15:28:29 +00001619 self, clone)
1620 return clone
1621
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001622 def createDocumentFragment(self):
1623 d = DocumentFragment()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001624 d.ownerDocument = self
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001625 return d
Fred Drake55c38192000-06-29 19:39:57 +00001626
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001627 def createElement(self, tagName):
1628 e = Element(tagName)
1629 e.ownerDocument = self
1630 return e
Fred Drake55c38192000-06-29 19:39:57 +00001631
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001632 def createTextNode(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001633 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001634 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001635 t = Text()
1636 t.data = data
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001637 t.ownerDocument = self
1638 return t
Fred Drake55c38192000-06-29 19:39:57 +00001639
Fred Drake87432f42001-04-04 14:09:46 +00001640 def createCDATASection(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001641 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001642 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001643 c = CDATASection()
1644 c.data = data
Fred Drake87432f42001-04-04 14:09:46 +00001645 c.ownerDocument = self
1646 return c
1647
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001648 def createComment(self, data):
1649 c = Comment(data)
1650 c.ownerDocument = self
1651 return c
Fred Drake55c38192000-06-29 19:39:57 +00001652
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001653 def createProcessingInstruction(self, target, data):
1654 p = ProcessingInstruction(target, data)
1655 p.ownerDocument = self
1656 return p
1657
1658 def createAttribute(self, qName):
1659 a = Attr(qName)
1660 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001661 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001662 return a
Fred Drake55c38192000-06-29 19:39:57 +00001663
1664 def createElementNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001665 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001666 e = Element(qualifiedName, namespaceURI, prefix)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001667 e.ownerDocument = self
1668 return e
Fred Drake55c38192000-06-29 19:39:57 +00001669
1670 def createAttributeNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001671 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001672 a = Attr(qualifiedName, namespaceURI, localName, prefix)
1673 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001674 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001675 return a
Fred Drake55c38192000-06-29 19:39:57 +00001676
Martin v. Löwis787354c2003-01-25 15:28:29 +00001677 # A couple of implementation-specific helpers to create node types
1678 # not supported by the W3C DOM specs:
1679
1680 def _create_entity(self, name, publicId, systemId, notationName):
1681 e = Entity(name, publicId, systemId, notationName)
1682 e.ownerDocument = self
1683 return e
1684
1685 def _create_notation(self, name, publicId, systemId):
1686 n = Notation(name, publicId, systemId)
1687 n.ownerDocument = self
1688 return n
1689
1690 def getElementById(self, id):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +00001691 if id in self._id_cache:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001692 return self._id_cache[id]
1693 if not (self._elem_info or self._magic_id_count):
1694 return None
1695
1696 stack = self._id_search_stack
1697 if stack is None:
1698 # we never searched before, or the cache has been cleared
1699 stack = [self.documentElement]
1700 self._id_search_stack = stack
1701 elif not stack:
1702 # Previous search was completed and cache is still valid;
1703 # no matching node.
1704 return None
1705
1706 result = None
1707 while stack:
1708 node = stack.pop()
1709 # add child elements to stack for continued searching
1710 stack.extend([child for child in node.childNodes
1711 if child.nodeType in _nodeTypes_with_children])
1712 # check this node
1713 info = self._get_elem_info(node)
1714 if info:
1715 # We have to process all ID attributes before
1716 # returning in order to get all the attributes set to
1717 # be IDs using Element.setIdAttribute*().
1718 for attr in node.attributes.values():
1719 if attr.namespaceURI:
1720 if info.isIdNS(attr.namespaceURI, attr.localName):
1721 self._id_cache[attr.value] = node
1722 if attr.value == id:
1723 result = node
1724 elif not node._magic_id_nodes:
1725 break
1726 elif info.isId(attr.name):
1727 self._id_cache[attr.value] = node
1728 if attr.value == id:
1729 result = node
1730 elif not node._magic_id_nodes:
1731 break
1732 elif attr._is_id:
1733 self._id_cache[attr.value] = node
1734 if attr.value == id:
1735 result = node
1736 elif node._magic_id_nodes == 1:
1737 break
1738 elif node._magic_id_nodes:
1739 for attr in node.attributes.values():
1740 if attr._is_id:
1741 self._id_cache[attr.value] = node
1742 if attr.value == id:
1743 result = node
1744 if result is not None:
1745 break
1746 return result
1747
Fred Drake1f549022000-09-24 05:21:58 +00001748 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001749 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drakefbe7b4f2001-07-04 06:25:53 +00001750
1751 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001752 return _get_elements_by_tagName_ns_helper(
1753 self, namespaceURI, localName, NodeList())
1754
1755 def isSupported(self, feature, version):
1756 return self.implementation.hasFeature(feature, version)
1757
1758 def importNode(self, node, deep):
1759 if node.nodeType == Node.DOCUMENT_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001760 raise xml.dom.NotSupportedErr("cannot import document nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001761 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001762 raise xml.dom.NotSupportedErr("cannot import document type nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001763 return _clone_node(node, deep, self)
Fred Drake55c38192000-06-29 19:39:57 +00001764
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001765 def writexml(self, writer, indent="", addindent="", newl="",
1766 encoding = None):
1767 if encoding is None:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001768 writer.write('<?xml version="1.0" ?>'+newl)
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001769 else:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001770 writer.write('<?xml version="1.0" encoding="%s"?>%s' % (encoding, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001771 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001772 node.writexml(writer, indent, addindent, newl)
Fred Drake55c38192000-06-29 19:39:57 +00001773
Martin v. Löwis787354c2003-01-25 15:28:29 +00001774 # DOM Level 3 (WD 9 April 2002)
1775
1776 def renameNode(self, n, namespaceURI, name):
1777 if n.ownerDocument is not self:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001778 raise xml.dom.WrongDocumentErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001779 "cannot rename nodes from other documents;\n"
1780 "expected %s,\nfound %s" % (self, n.ownerDocument))
1781 if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001782 raise xml.dom.NotSupportedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001783 "renameNode() only applies to element and attribute nodes")
1784 if namespaceURI != EMPTY_NAMESPACE:
1785 if ':' in name:
1786 prefix, localName = name.split(':', 1)
1787 if ( prefix == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001788 and namespaceURI != xml.dom.XMLNS_NAMESPACE):
1789 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001790 "illegal use of 'xmlns' prefix")
1791 else:
1792 if ( name == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001793 and namespaceURI != xml.dom.XMLNS_NAMESPACE
Martin v. Löwis787354c2003-01-25 15:28:29 +00001794 and n.nodeType == Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001795 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001796 "illegal use of the 'xmlns' attribute")
1797 prefix = None
1798 localName = name
1799 else:
1800 prefix = None
1801 localName = None
1802 if n.nodeType == Node.ATTRIBUTE_NODE:
1803 element = n.ownerElement
1804 if element is not None:
1805 is_id = n._is_id
1806 element.removeAttributeNode(n)
1807 else:
1808 element = None
1809 # avoid __setattr__
1810 d = n.__dict__
1811 d['prefix'] = prefix
1812 d['localName'] = localName
1813 d['namespaceURI'] = namespaceURI
1814 d['nodeName'] = name
1815 if n.nodeType == Node.ELEMENT_NODE:
1816 d['tagName'] = name
1817 else:
1818 # attribute node
1819 d['name'] = name
1820 if element is not None:
1821 element.setAttributeNode(n)
1822 if is_id:
1823 element.setIdAttributeNode(n)
1824 # It's not clear from a semantic perspective whether we should
1825 # call the user data handlers for the NODE_RENAMED event since
1826 # we're re-using the existing node. The draft spec has been
1827 # interpreted as meaning "no, don't call the handler unless a
1828 # new node is created."
1829 return n
1830
1831defproperty(Document, "documentElement",
1832 doc="Top-level element of this document.")
1833
1834
1835def _clone_node(node, deep, newOwnerDocument):
1836 """
1837 Clone a node and give it the new owner document.
1838 Called by Node.cloneNode and Document.importNode
1839 """
1840 if node.ownerDocument.isSameNode(newOwnerDocument):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001841 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001842 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001843 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001844 if node.nodeType == Node.ELEMENT_NODE:
1845 clone = newOwnerDocument.createElementNS(node.namespaceURI,
1846 node.nodeName)
1847 for attr in node.attributes.values():
1848 clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
1849 a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)
1850 a.specified = attr.specified
1851
1852 if deep:
1853 for child in node.childNodes:
1854 c = _clone_node(child, deep, newOwnerDocument)
1855 clone.appendChild(c)
1856
1857 elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
1858 clone = newOwnerDocument.createDocumentFragment()
1859 if deep:
1860 for child in node.childNodes:
1861 c = _clone_node(child, deep, newOwnerDocument)
1862 clone.appendChild(c)
1863
1864 elif node.nodeType == Node.TEXT_NODE:
1865 clone = newOwnerDocument.createTextNode(node.data)
1866 elif node.nodeType == Node.CDATA_SECTION_NODE:
1867 clone = newOwnerDocument.createCDATASection(node.data)
1868 elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
1869 clone = newOwnerDocument.createProcessingInstruction(node.target,
1870 node.data)
1871 elif node.nodeType == Node.COMMENT_NODE:
1872 clone = newOwnerDocument.createComment(node.data)
1873 elif node.nodeType == Node.ATTRIBUTE_NODE:
1874 clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
1875 node.nodeName)
1876 clone.specified = True
1877 clone.value = node.value
1878 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
1879 assert node.ownerDocument is not newOwnerDocument
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001880 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001881 clone = newOwnerDocument.implementation.createDocumentType(
1882 node.name, node.publicId, node.systemId)
1883 clone.ownerDocument = newOwnerDocument
1884 if deep:
1885 clone.entities._seq = []
1886 clone.notations._seq = []
1887 for n in node.notations._seq:
1888 notation = Notation(n.nodeName, n.publicId, n.systemId)
1889 notation.ownerDocument = newOwnerDocument
1890 clone.notations._seq.append(notation)
1891 if hasattr(n, '_call_user_data_handler'):
1892 n._call_user_data_handler(operation, n, notation)
1893 for e in node.entities._seq:
1894 entity = Entity(e.nodeName, e.publicId, e.systemId,
1895 e.notationName)
1896 entity.actualEncoding = e.actualEncoding
1897 entity.encoding = e.encoding
1898 entity.version = e.version
1899 entity.ownerDocument = newOwnerDocument
1900 clone.entities._seq.append(entity)
1901 if hasattr(e, '_call_user_data_handler'):
1902 e._call_user_data_handler(operation, n, entity)
1903 else:
1904 # Note the cloning of Document and DocumentType nodes is
1905 # implemenetation specific. minidom handles those cases
1906 # directly in the cloneNode() methods.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001907 raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001908
1909 # Check for _call_user_data_handler() since this could conceivably
1910 # used with other DOM implementations (one of the FourThought
1911 # DOMs, perhaps?).
1912 if hasattr(node, '_call_user_data_handler'):
1913 node._call_user_data_handler(operation, node, clone)
1914 return clone
1915
1916
1917def _nssplit(qualifiedName):
1918 fields = qualifiedName.split(':', 1)
1919 if len(fields) == 2:
1920 return fields
1921 else:
1922 return (None, fields[0])
1923
1924
Martin v. Löwis787354c2003-01-25 15:28:29 +00001925def _do_pulldom_parse(func, args, kwargs):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001926 events = func(*args, **kwargs)
Fred Drake1f549022000-09-24 05:21:58 +00001927 toktype, rootNode = events.getEvent()
1928 events.expandNode(rootNode)
Martin v. Löwisb417be22001-02-06 01:16:06 +00001929 events.clear()
Fred Drake55c38192000-06-29 19:39:57 +00001930 return rootNode
1931
Martin v. Löwis787354c2003-01-25 15:28:29 +00001932def parse(file, parser=None, bufsize=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001933 """Parse a file into a DOM by filename or file object."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001934 if parser is None and not bufsize:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001935 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001936 return expatbuilder.parse(file)
1937 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001938 from xml.dom import pulldom
Raymond Hettingerff41c482003-04-06 09:01:11 +00001939 return _do_pulldom_parse(pulldom.parse, (file,),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001940 {'parser': parser, 'bufsize': bufsize})
Fred Drake55c38192000-06-29 19:39:57 +00001941
Martin v. Löwis787354c2003-01-25 15:28:29 +00001942def parseString(string, parser=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001943 """Parse a file into a DOM from a string."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001944 if parser is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001945 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001946 return expatbuilder.parseString(string)
1947 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001948 from xml.dom import pulldom
Martin v. Löwis787354c2003-01-25 15:28:29 +00001949 return _do_pulldom_parse(pulldom.parseString, (string,),
1950 {'parser': parser})
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001951
Martin v. Löwis787354c2003-01-25 15:28:29 +00001952def getDOMImplementation(features=None):
1953 if features:
Christian Heimesc9543e42007-11-28 08:28:28 +00001954 if isinstance(features, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001955 features = domreg._parse_feature_string(features)
1956 for f, v in features:
1957 if not Document.implementation.hasFeature(f, v):
1958 return None
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001959 return Document.implementation