blob: 3529bd33ef080fa36419f8bf6bc75bcaa0cbe6c3 [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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000017import xml.dom
Fred Drake55c38192000-06-29 19:39:57 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg
20from xml.dom.minicompat import *
21from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS
Fred Drake3ac6a092001-09-28 04:33:06 +000022
Martin v. Löwis787354c2003-01-25 15:28:29 +000023# This is used by the ID-cache invalidation checks; the list isn't
24# actually complete, since the nodes being checked will never be the
25# DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is
26# the node being added or removed, not the node being modified.)
27#
Thomas Wouters0e3f5912006-08-11 14:57:12 +000028_nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE,
29 xml.dom.Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis95700f72002-03-15 13:51:59 +000030
Fred Drake3ac6a092001-09-28 04:33:06 +000031
Thomas Wouters0e3f5912006-08-11 14:57:12 +000032class Node(xml.dom.Node):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000033 namespaceURI = None # this is non-null only for elements and attributes
Fred Drake575712e2001-09-28 20:25:45 +000034 parentNode = None
35 ownerDocument = None
Martin v. Löwis787354c2003-01-25 15:28:29 +000036 nextSibling = None
37 previousSibling = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +000038
Martin v. Löwis787354c2003-01-25 15:28:29 +000039 prefix = EMPTY_PREFIX # non-null only for NS elements and attributes
Fred Drake55c38192000-06-29 19:39:57 +000040
Jack Diederich4dafcc42006-11-28 19:15:13 +000041 def __bool__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +000042 return True
Fred Drake55c38192000-06-29 19:39:57 +000043
Martin v. Löwis7d650ca2002-06-30 15:05:00 +000044 def toxml(self, encoding = None):
45 return self.toprettyxml("", "", encoding)
Fred Drake55c38192000-06-29 19:39:57 +000046
Martin v. Löwis7d650ca2002-06-30 15:05:00 +000047 def toprettyxml(self, indent="\t", newl="\n", encoding = None):
Martin v. Löwiscb67ea12001-03-31 16:30:40 +000048 # indent = the indentation string to prepend, per level
49 # newl = the newline string to append
50 writer = _get_StringIO()
Martin v. Löwis7d650ca2002-06-30 15:05:00 +000051 if encoding is not None:
52 import codecs
53 # Can't use codecs.getwriter to preserve 2.0 compatibility
54 writer = codecs.lookup(encoding)[3](writer)
55 if self.nodeType == Node.DOCUMENT_NODE:
56 # Can pass encoding only to document, to put it into XML header
57 self.writexml(writer, "", indent, newl, encoding)
58 else:
59 self.writexml(writer, "", indent, newl)
Martin v. Löwiscb67ea12001-03-31 16:30:40 +000060 return writer.getvalue()
Martin v. Löwis46fa39a2001-02-06 00:14:08 +000061
Fred Drake1f549022000-09-24 05:21:58 +000062 def hasChildNodes(self):
63 if self.childNodes:
Martin v. Löwis787354c2003-01-25 15:28:29 +000064 return True
Fred Drake1f549022000-09-24 05:21:58 +000065 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +000066 return False
67
68 def _get_childNodes(self):
69 return self.childNodes
Fred Drake55c38192000-06-29 19:39:57 +000070
Fred Drake1f549022000-09-24 05:21:58 +000071 def _get_firstChild(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +000072 if self.childNodes:
73 return self.childNodes[0]
Paul Prescod73678da2000-07-01 04:58:47 +000074
Fred Drake1f549022000-09-24 05:21:58 +000075 def _get_lastChild(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +000076 if self.childNodes:
77 return self.childNodes[-1]
Paul Prescod73678da2000-07-01 04:58:47 +000078
Fred Drake1f549022000-09-24 05:21:58 +000079 def insertBefore(self, newChild, refChild):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000080 if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
Fred Drakee50959a2001-12-06 04:32:18 +000081 for c in tuple(newChild.childNodes):
Martin v. Löwis126f2f62001-03-13 10:50:13 +000082 self.insertBefore(c, refChild)
83 ### The DOM does not clearly specify what to return in this case
84 return newChild
Martin v. Löwis787354c2003-01-25 15:28:29 +000085 if newChild.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000086 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +000087 "%s cannot be child of %s" % (repr(newChild), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +000088 if newChild.parentNode is not None:
89 newChild.parentNode.removeChild(newChild)
Fred Drake4ccf4a12000-11-21 22:02:22 +000090 if refChild is None:
91 self.appendChild(newChild)
92 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +000093 try:
94 index = self.childNodes.index(refChild)
95 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000096 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +000097 if newChild.nodeType in _nodeTypes_with_children:
98 _clear_id_cache(self)
Fred Drake4ccf4a12000-11-21 22:02:22 +000099 self.childNodes.insert(index, newChild)
100 newChild.nextSibling = refChild
101 refChild.previousSibling = newChild
102 if index:
103 node = self.childNodes[index-1]
104 node.nextSibling = newChild
105 newChild.previousSibling = node
106 else:
107 newChild.previousSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000108 newChild.parentNode = self
Fred Drake4ccf4a12000-11-21 22:02:22 +0000109 return newChild
Fred Drake55c38192000-06-29 19:39:57 +0000110
Fred Drake1f549022000-09-24 05:21:58 +0000111 def appendChild(self, node):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000112 if node.nodeType == self.DOCUMENT_FRAGMENT_NODE:
Fred Drakee50959a2001-12-06 04:32:18 +0000113 for c in tuple(node.childNodes):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000114 self.appendChild(c)
115 ### The DOM does not clearly specify what to return in this case
116 return node
Martin v. Löwis787354c2003-01-25 15:28:29 +0000117 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000118 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000119 "%s cannot be child of %s" % (repr(node), repr(self)))
120 elif node.nodeType in _nodeTypes_with_children:
121 _clear_id_cache(self)
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000122 if node.parentNode is not None:
123 node.parentNode.removeChild(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000124 _append_child(self, node)
Fred Drake13a30692000-10-09 20:04:16 +0000125 node.nextSibling = None
Paul Prescod73678da2000-07-01 04:58:47 +0000126 return node
127
Fred Drake1f549022000-09-24 05:21:58 +0000128 def replaceChild(self, newChild, oldChild):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000129 if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
130 refChild = oldChild.nextSibling
131 self.removeChild(oldChild)
132 return self.insertBefore(newChild, refChild)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000133 if newChild.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000134 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000135 "%s cannot be child of %s" % (repr(newChild), repr(self)))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000136 if newChild is oldChild:
137 return
Andrew M. Kuchling841d25e2005-11-22 19:03:16 +0000138 if newChild.parentNode is not None:
139 newChild.parentNode.removeChild(newChild)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000140 try:
141 index = self.childNodes.index(oldChild)
142 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 raise xml.dom.NotFoundErr()
Fred Drake4ccf4a12000-11-21 22:02:22 +0000144 self.childNodes[index] = newChild
Martin v. Löwis787354c2003-01-25 15:28:29 +0000145 newChild.parentNode = self
146 oldChild.parentNode = None
147 if (newChild.nodeType in _nodeTypes_with_children
148 or oldChild.nodeType in _nodeTypes_with_children):
149 _clear_id_cache(self)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000150 newChild.nextSibling = oldChild.nextSibling
151 newChild.previousSibling = oldChild.previousSibling
Martin v. Löwis156c3372000-12-28 18:40:56 +0000152 oldChild.nextSibling = None
Fred Drake4ccf4a12000-11-21 22:02:22 +0000153 oldChild.previousSibling = None
Martin v. Löwis156c3372000-12-28 18:40:56 +0000154 if newChild.previousSibling:
155 newChild.previousSibling.nextSibling = newChild
156 if newChild.nextSibling:
157 newChild.nextSibling.previousSibling = newChild
Fred Drake4ccf4a12000-11-21 22:02:22 +0000158 return oldChild
Paul Prescod73678da2000-07-01 04:58:47 +0000159
Fred Drake1f549022000-09-24 05:21:58 +0000160 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000161 try:
162 self.childNodes.remove(oldChild)
163 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000164 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000165 if oldChild.nextSibling is not None:
166 oldChild.nextSibling.previousSibling = oldChild.previousSibling
167 if oldChild.previousSibling is not None:
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000168 oldChild.previousSibling.nextSibling = oldChild.nextSibling
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +0000169 oldChild.nextSibling = oldChild.previousSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000170 if oldChild.nodeType in _nodeTypes_with_children:
171 _clear_id_cache(self)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000172
Martin v. Löwis787354c2003-01-25 15:28:29 +0000173 oldChild.parentNode = None
Fred Drake4ccf4a12000-11-21 22:02:22 +0000174 return oldChild
175
176 def normalize(self):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000177 L = []
178 for child in self.childNodes:
179 if child.nodeType == Node.TEXT_NODE:
180 data = child.data
181 if data and L and L[-1].nodeType == child.nodeType:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000182 # collapse text node
183 node = L[-1]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000184 node.data = node.data + child.data
Fred Drake4ccf4a12000-11-21 22:02:22 +0000185 node.nextSibling = child.nextSibling
186 child.unlink()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000187 elif data:
188 if L:
189 L[-1].nextSibling = child
190 child.previousSibling = L[-1]
191 else:
192 child.previousSibling = None
193 L.append(child)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000194 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000195 # empty text node; discard
196 child.unlink()
197 else:
198 if L:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000199 L[-1].nextSibling = child
200 child.previousSibling = L[-1]
Fred Drakef7cf40d2000-12-14 18:16:11 +0000201 else:
202 child.previousSibling = None
203 L.append(child)
204 if child.nodeType == Node.ELEMENT_NODE:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000205 child.normalize()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000206 self.childNodes[:] = L
Paul Prescod73678da2000-07-01 04:58:47 +0000207
Fred Drake1f549022000-09-24 05:21:58 +0000208 def cloneNode(self, deep):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000209 return _clone_node(self, deep, self.ownerDocument or self)
Fred Drake55c38192000-06-29 19:39:57 +0000210
Martin v. Löwis787354c2003-01-25 15:28:29 +0000211 def isSupported(self, feature, version):
212 return self.ownerDocument.implementation.hasFeature(feature, version)
213
214 def _get_localName(self):
215 # Overridden in Element and Attr where localName can be Non-Null
216 return None
217
218 # Node interfaces from Level 3 (WD 9 April 2002)
Fred Drake25239772001-02-02 19:40:19 +0000219
220 def isSameNode(self, other):
221 return self is other
222
Martin v. Löwis787354c2003-01-25 15:28:29 +0000223 def getInterface(self, feature):
224 if self.isSupported(feature, None):
225 return self
226 else:
227 return None
228
229 # The "user data" functions use a dictionary that is only present
230 # if some user data has been set, so be careful not to assume it
231 # exists.
232
233 def getUserData(self, key):
234 try:
235 return self._user_data[key][0]
236 except (AttributeError, KeyError):
237 return None
238
239 def setUserData(self, key, data, handler):
240 old = None
241 try:
242 d = self._user_data
243 except AttributeError:
244 d = {}
245 self._user_data = d
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000246 if key in d:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000247 old = d[key][0]
248 if data is None:
249 # ignore handlers passed for None
250 handler = None
251 if old is not None:
252 del d[key]
253 else:
254 d[key] = (data, handler)
255 return old
256
257 def _call_user_data_handler(self, operation, src, dst):
258 if hasattr(self, "_user_data"):
Brett Cannon861fd6f2007-02-21 22:05:37 +0000259 for key, (data, handler) in list(self._user_data.items()):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000260 if handler is not None:
261 handler.handle(operation, key, data, src, dst)
262
Fred Drake25239772001-02-02 19:40:19 +0000263 # minidom-specific API:
264
Fred Drake1f549022000-09-24 05:21:58 +0000265 def unlink(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000266 self.parentNode = self.ownerDocument = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000267 if self.childNodes:
268 for child in self.childNodes:
269 child.unlink()
270 self.childNodes = NodeList()
Paul Prescod4221ff02000-10-13 20:11:42 +0000271 self.previousSibling = None
272 self.nextSibling = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000273
274defproperty(Node, "firstChild", doc="First child node, or None.")
275defproperty(Node, "lastChild", doc="Last child node, or None.")
276defproperty(Node, "localName", doc="Namespace-local name of this node.")
277
278
279def _append_child(self, node):
280 # fast path with less checks; usable by DOM builders if careful
281 childNodes = self.childNodes
282 if childNodes:
283 last = childNodes[-1]
284 node.__dict__["previousSibling"] = last
285 last.__dict__["nextSibling"] = node
286 childNodes.append(node)
287 node.__dict__["parentNode"] = self
288
289def _in_document(node):
290 # return True iff node is part of a document tree
291 while node is not None:
292 if node.nodeType == Node.DOCUMENT_NODE:
293 return True
294 node = node.parentNode
295 return False
Fred Drake55c38192000-06-29 19:39:57 +0000296
Fred Drake1f549022000-09-24 05:21:58 +0000297def _write_data(writer, data):
Fred Drake55c38192000-06-29 19:39:57 +0000298 "Writes datachars to writer."
Martin v. Löwis787354c2003-01-25 15:28:29 +0000299 data = data.replace("&", "&amp;").replace("<", "&lt;")
300 data = data.replace("\"", "&quot;").replace(">", "&gt;")
Fred Drake55c38192000-06-29 19:39:57 +0000301 writer.write(data)
302
Martin v. Löwis787354c2003-01-25 15:28:29 +0000303def _get_elements_by_tagName_helper(parent, name, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000304 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000305 if node.nodeType == Node.ELEMENT_NODE and \
306 (name == "*" or node.tagName == name):
307 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000308 _get_elements_by_tagName_helper(node, name, rc)
Fred Drake55c38192000-06-29 19:39:57 +0000309 return rc
310
Martin v. Löwis787354c2003-01-25 15:28:29 +0000311def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000312 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000313 if node.nodeType == Node.ELEMENT_NODE:
Martin v. Löwised525fb2001-06-03 14:06:42 +0000314 if ((localName == "*" or node.localName == localName) and
Fred Drake1f549022000-09-24 05:21:58 +0000315 (nsURI == "*" or node.namespaceURI == nsURI)):
316 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000317 _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000318 return rc
Fred Drake55c38192000-06-29 19:39:57 +0000319
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000320class DocumentFragment(Node):
321 nodeType = Node.DOCUMENT_FRAGMENT_NODE
322 nodeName = "#document-fragment"
323 nodeValue = None
324 attributes = None
325 parentNode = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000326 _child_node_types = (Node.ELEMENT_NODE,
327 Node.TEXT_NODE,
328 Node.CDATA_SECTION_NODE,
329 Node.ENTITY_REFERENCE_NODE,
330 Node.PROCESSING_INSTRUCTION_NODE,
331 Node.COMMENT_NODE,
332 Node.NOTATION_NODE)
333
334 def __init__(self):
335 self.childNodes = NodeList()
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000336
337
Fred Drake55c38192000-06-29 19:39:57 +0000338class Attr(Node):
Fred Drake1f549022000-09-24 05:21:58 +0000339 nodeType = Node.ATTRIBUTE_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +0000340 attributes = None
341 ownerElement = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000342 specified = False
343 _is_id = False
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000344
Martin v. Löwis787354c2003-01-25 15:28:29 +0000345 _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE)
346
347 def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None,
348 prefix=None):
Fred Drake55c38192000-06-29 19:39:57 +0000349 # skip setattr for performance
Fred Drake4ccf4a12000-11-21 22:02:22 +0000350 d = self.__dict__
Fred Drake4ccf4a12000-11-21 22:02:22 +0000351 d["nodeName"] = d["name"] = qName
352 d["namespaceURI"] = namespaceURI
353 d["prefix"] = prefix
Martin v. Löwis787354c2003-01-25 15:28:29 +0000354 d['childNodes'] = NodeList()
355
356 # Add the single child node that represents the value of the attr
357 self.childNodes.append(Text())
358
Paul Prescod73678da2000-07-01 04:58:47 +0000359 # nodeValue and value are set elsewhere
Fred Drake55c38192000-06-29 19:39:57 +0000360
Martin v. Löwis787354c2003-01-25 15:28:29 +0000361 def _get_localName(self):
Alex Martelli0ee43512006-08-21 19:53:20 +0000362 if 'localName' in self.__dict__:
363 return self.__dict__['localName']
Martin v. Löwis787354c2003-01-25 15:28:29 +0000364 return self.nodeName.split(":", 1)[-1]
365
366 def _get_name(self):
367 return self.name
368
369 def _get_specified(self):
370 return self.specified
371
Fred Drake1f549022000-09-24 05:21:58 +0000372 def __setattr__(self, name, value):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000373 d = self.__dict__
Fred Drake1f549022000-09-24 05:21:58 +0000374 if name in ("value", "nodeValue"):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000375 d["value"] = d["nodeValue"] = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000376 d2 = self.childNodes[0].__dict__
377 d2["data"] = d2["nodeValue"] = value
378 if self.ownerElement is not None:
379 _clear_id_cache(self.ownerElement)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000380 elif name in ("name", "nodeName"):
381 d["name"] = d["nodeName"] = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000382 if self.ownerElement is not None:
383 _clear_id_cache(self.ownerElement)
Fred Drake55c38192000-06-29 19:39:57 +0000384 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000385 d[name] = value
Fred Drake55c38192000-06-29 19:39:57 +0000386
Martin v. Löwis995359c2003-01-26 08:59:32 +0000387 def _set_prefix(self, prefix):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000388 nsuri = self.namespaceURI
Martin v. Löwis995359c2003-01-26 08:59:32 +0000389 if prefix == "xmlns":
390 if nsuri and nsuri != XMLNS_NAMESPACE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000391 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000392 "illegal use of 'xmlns' prefix for the wrong namespace")
393 d = self.__dict__
394 d['prefix'] = prefix
395 if prefix is None:
396 newName = self.localName
397 else:
Martin v. Löwis995359c2003-01-26 08:59:32 +0000398 newName = "%s:%s" % (prefix, self.localName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000399 if self.ownerElement:
400 _clear_id_cache(self.ownerElement)
401 d['nodeName'] = d['name'] = newName
402
403 def _set_value(self, value):
404 d = self.__dict__
405 d['value'] = d['nodeValue'] = value
406 if self.ownerElement:
407 _clear_id_cache(self.ownerElement)
408 self.childNodes[0].data = value
409
410 def unlink(self):
411 # This implementation does not call the base implementation
412 # since most of that is not needed, and the expense of the
413 # method call is not warranted. We duplicate the removal of
414 # children, but that's all we needed from the base class.
415 elem = self.ownerElement
416 if elem is not None:
417 del elem._attrs[self.nodeName]
418 del elem._attrsNS[(self.namespaceURI, self.localName)]
419 if self._is_id:
420 self._is_id = False
421 elem._magic_id_nodes -= 1
422 self.ownerDocument._magic_id_count -= 1
423 for child in self.childNodes:
424 child.unlink()
425 del self.childNodes[:]
426
427 def _get_isId(self):
428 if self._is_id:
429 return True
430 doc = self.ownerDocument
431 elem = self.ownerElement
432 if doc is None or elem is None:
433 return False
434
435 info = doc._get_elem_info(elem)
436 if info is None:
437 return False
438 if self.namespaceURI:
439 return info.isIdNS(self.namespaceURI, self.localName)
440 else:
441 return info.isId(self.nodeName)
442
443 def _get_schemaType(self):
444 doc = self.ownerDocument
445 elem = self.ownerElement
446 if doc is None or elem is None:
447 return _no_type
448
449 info = doc._get_elem_info(elem)
450 if info is None:
451 return _no_type
452 if self.namespaceURI:
453 return info.getAttributeTypeNS(self.namespaceURI, self.localName)
454 else:
455 return info.getAttributeType(self.nodeName)
456
457defproperty(Attr, "isId", doc="True if this attribute is an ID.")
458defproperty(Attr, "localName", doc="Namespace-local name of this attribute.")
459defproperty(Attr, "schemaType", doc="Schema type for this attribute.")
Fred Drake4ccf4a12000-11-21 22:02:22 +0000460
Fred Drakef7cf40d2000-12-14 18:16:11 +0000461
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000462class NamedNodeMap(object):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000463 """The attribute list is a transient interface to the underlying
464 dictionaries. Mutations here will change the underlying element's
Fred Drakef7cf40d2000-12-14 18:16:11 +0000465 dictionary.
466
467 Ordering is imposed artificially and does not reflect the order of
468 attributes as found in an input document.
469 """
Fred Drake4ccf4a12000-11-21 22:02:22 +0000470
Martin v. Löwis787354c2003-01-25 15:28:29 +0000471 __slots__ = ('_attrs', '_attrsNS', '_ownerElement')
472
Fred Drake2998a552001-12-06 18:27:48 +0000473 def __init__(self, attrs, attrsNS, ownerElement):
Fred Drake1f549022000-09-24 05:21:58 +0000474 self._attrs = attrs
475 self._attrsNS = attrsNS
Fred Drake2998a552001-12-06 18:27:48 +0000476 self._ownerElement = ownerElement
Fred Drakef7cf40d2000-12-14 18:16:11 +0000477
Martin v. Löwis787354c2003-01-25 15:28:29 +0000478 def _get_length(self):
479 return len(self._attrs)
Fred Drake55c38192000-06-29 19:39:57 +0000480
Fred Drake1f549022000-09-24 05:21:58 +0000481 def item(self, index):
Fred Drake55c38192000-06-29 19:39:57 +0000482 try:
Brett Cannon861fd6f2007-02-21 22:05:37 +0000483 return self[list(self._attrs.keys())[index]]
Fred Drake55c38192000-06-29 19:39:57 +0000484 except IndexError:
485 return None
Fred Drake55c38192000-06-29 19:39:57 +0000486
Fred Drake1f549022000-09-24 05:21:58 +0000487 def items(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000488 L = []
489 for node in self._attrs.values():
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000490 L.append((node.nodeName, node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000491 return L
Fred Drake1f549022000-09-24 05:21:58 +0000492
493 def itemsNS(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000494 L = []
495 for node in self._attrs.values():
Fred Drake49a5d032001-11-30 22:21:58 +0000496 L.append(((node.namespaceURI, node.localName), node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000497 return L
Fred Drake16f63292000-10-23 18:09:50 +0000498
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000499 def __contains__(self, key):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000500 if isinstance(key, StringTypes):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000501 return key in self._attrs
Martin v. Löwis787354c2003-01-25 15:28:29 +0000502 else:
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000503 return key in self._attrsNS
Martin v. Löwis787354c2003-01-25 15:28:29 +0000504
Fred Drake1f549022000-09-24 05:21:58 +0000505 def keys(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000506 return self._attrs.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000507
Fred Drake1f549022000-09-24 05:21:58 +0000508 def keysNS(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000509 return self._attrsNS.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000510
Fred Drake1f549022000-09-24 05:21:58 +0000511 def values(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000512 return self._attrs.values()
Fred Drake55c38192000-06-29 19:39:57 +0000513
Martin v. Löwis787354c2003-01-25 15:28:29 +0000514 def get(self, name, value=None):
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000515 return self._attrs.get(name, value)
516
Martin v. Löwis787354c2003-01-25 15:28:29 +0000517 __len__ = _get_length
Fred Drake55c38192000-06-29 19:39:57 +0000518
Fred Drake1f549022000-09-24 05:21:58 +0000519 def __cmp__(self, other):
520 if self._attrs is getattr(other, "_attrs", None):
Fred Drake55c38192000-06-29 19:39:57 +0000521 return 0
Fred Drake16f63292000-10-23 18:09:50 +0000522 else:
Fred Drake1f549022000-09-24 05:21:58 +0000523 return cmp(id(self), id(other))
Fred Drake55c38192000-06-29 19:39:57 +0000524
Fred Drake1f549022000-09-24 05:21:58 +0000525 def __getitem__(self, attname_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000526 if isinstance(attname_or_tuple, tuple):
Paul Prescod73678da2000-07-01 04:58:47 +0000527 return self._attrsNS[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000528 else:
Paul Prescod73678da2000-07-01 04:58:47 +0000529 return self._attrs[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000530
Paul Prescod1e688272000-07-01 19:21:47 +0000531 # same as set
Fred Drake1f549022000-09-24 05:21:58 +0000532 def __setitem__(self, attname, value):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000533 if isinstance(value, StringTypes):
534 try:
535 node = self._attrs[attname]
536 except KeyError:
537 node = Attr(attname)
538 node.ownerDocument = self._ownerElement.ownerDocument
Martin v. Löwis995359c2003-01-26 08:59:32 +0000539 self.setNamedItem(node)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000540 node.value = value
Paul Prescod1e688272000-07-01 19:21:47 +0000541 else:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000542 if not isinstance(value, Attr):
543 raise TypeError, "value must be a string or Attr object"
Fred Drake1f549022000-09-24 05:21:58 +0000544 node = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000545 self.setNamedItem(node)
546
547 def getNamedItem(self, name):
548 try:
549 return self._attrs[name]
550 except KeyError:
551 return None
552
553 def getNamedItemNS(self, namespaceURI, localName):
554 try:
555 return self._attrsNS[(namespaceURI, localName)]
556 except KeyError:
557 return None
558
559 def removeNamedItem(self, name):
560 n = self.getNamedItem(name)
561 if n is not None:
562 _clear_id_cache(self._ownerElement)
563 del self._attrs[n.nodeName]
564 del self._attrsNS[(n.namespaceURI, n.localName)]
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000565 if 'ownerElement' in n.__dict__:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000566 n.__dict__['ownerElement'] = None
567 return n
568 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000569 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000570
571 def removeNamedItemNS(self, namespaceURI, localName):
572 n = self.getNamedItemNS(namespaceURI, localName)
573 if n is not None:
574 _clear_id_cache(self._ownerElement)
575 del self._attrsNS[(n.namespaceURI, n.localName)]
576 del self._attrs[n.nodeName]
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000577 if 'ownerElement' in n.__dict__:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000578 n.__dict__['ownerElement'] = None
579 return n
580 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000581 raise xml.dom.NotFoundErr()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000582
583 def setNamedItem(self, node):
Andrew M. Kuchlingbc8f72c2001-02-21 01:30:26 +0000584 if not isinstance(node, Attr):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000585 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000586 "%s cannot be child of %s" % (repr(node), repr(self)))
Fred Drakef7cf40d2000-12-14 18:16:11 +0000587 old = self._attrs.get(node.name)
Paul Prescod1e688272000-07-01 19:21:47 +0000588 if old:
589 old.unlink()
Fred Drake1f549022000-09-24 05:21:58 +0000590 self._attrs[node.name] = node
591 self._attrsNS[(node.namespaceURI, node.localName)] = node
Fred Drake2998a552001-12-06 18:27:48 +0000592 node.ownerElement = self._ownerElement
Martin v. Löwis787354c2003-01-25 15:28:29 +0000593 _clear_id_cache(node.ownerElement)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000594 return old
595
596 def setNamedItemNS(self, node):
597 return self.setNamedItem(node)
Paul Prescod73678da2000-07-01 04:58:47 +0000598
Fred Drake1f549022000-09-24 05:21:58 +0000599 def __delitem__(self, attname_or_tuple):
600 node = self[attname_or_tuple]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000601 _clear_id_cache(node.ownerElement)
Paul Prescod73678da2000-07-01 04:58:47 +0000602 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000603
604 def __getstate__(self):
605 return self._attrs, self._attrsNS, self._ownerElement
606
607 def __setstate__(self, state):
608 self._attrs, self._attrsNS, self._ownerElement = state
609
610defproperty(NamedNodeMap, "length",
611 doc="Number of nodes in the NamedNodeMap.")
Fred Drakef7cf40d2000-12-14 18:16:11 +0000612
613AttributeList = NamedNodeMap
614
Fred Drake1f549022000-09-24 05:21:58 +0000615
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000616class TypeInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000617 __slots__ = 'namespace', 'name'
618
619 def __init__(self, namespace, name):
620 self.namespace = namespace
621 self.name = name
622
623 def __repr__(self):
624 if self.namespace:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000625 return "<TypeInfo %r (from %r)>" % (self.name, self.namespace)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000626 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000627 return "<TypeInfo %r>" % self.name
Martin v. Löwis787354c2003-01-25 15:28:29 +0000628
629 def _get_name(self):
630 return self.name
631
632 def _get_namespace(self):
633 return self.namespace
634
635_no_type = TypeInfo(None, None)
636
Martin v. Löwisa2fda0d2000-10-07 12:10:28 +0000637class Element(Node):
Fred Drake1f549022000-09-24 05:21:58 +0000638 nodeType = Node.ELEMENT_NODE
Martin v. Löwis787354c2003-01-25 15:28:29 +0000639 nodeValue = None
640 schemaType = _no_type
641
642 _magic_id_nodes = 0
643
644 _child_node_types = (Node.ELEMENT_NODE,
645 Node.PROCESSING_INSTRUCTION_NODE,
646 Node.COMMENT_NODE,
647 Node.TEXT_NODE,
648 Node.CDATA_SECTION_NODE,
649 Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000650
Fred Drake49a5d032001-11-30 22:21:58 +0000651 def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None,
Fred Drake1f549022000-09-24 05:21:58 +0000652 localName=None):
Fred Drake55c38192000-06-29 19:39:57 +0000653 self.tagName = self.nodeName = tagName
Fred Drake1f549022000-09-24 05:21:58 +0000654 self.prefix = prefix
655 self.namespaceURI = namespaceURI
Martin v. Löwis787354c2003-01-25 15:28:29 +0000656 self.childNodes = NodeList()
Fred Drake55c38192000-06-29 19:39:57 +0000657
Fred Drake4ccf4a12000-11-21 22:02:22 +0000658 self._attrs = {} # attributes are double-indexed:
659 self._attrsNS = {} # tagName -> Attribute
660 # URI,localName -> Attribute
661 # in the future: consider lazy generation
662 # of attribute objects this is too tricky
663 # for now because of headaches with
664 # namespaces.
665
Martin v. Löwis787354c2003-01-25 15:28:29 +0000666 def _get_localName(self):
Alex Martelli0ee43512006-08-21 19:53:20 +0000667 if 'localName' in self.__dict__:
668 return self.__dict__['localName']
Martin v. Löwis787354c2003-01-25 15:28:29 +0000669 return self.tagName.split(":", 1)[-1]
670
671 def _get_tagName(self):
672 return self.tagName
Fred Drake4ccf4a12000-11-21 22:02:22 +0000673
674 def unlink(self):
Brett Cannon861fd6f2007-02-21 22:05:37 +0000675 for attr in list(self._attrs.values()):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000676 attr.unlink()
677 self._attrs = None
678 self._attrsNS = None
679 Node.unlink(self)
Fred Drake55c38192000-06-29 19:39:57 +0000680
Fred Drake1f549022000-09-24 05:21:58 +0000681 def getAttribute(self, attname):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000682 try:
683 return self._attrs[attname].value
684 except KeyError:
685 return ""
Fred Drake55c38192000-06-29 19:39:57 +0000686
Fred Drake1f549022000-09-24 05:21:58 +0000687 def getAttributeNS(self, namespaceURI, localName):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000688 try:
689 return self._attrsNS[(namespaceURI, localName)].value
690 except KeyError:
691 return ""
Fred Drake1f549022000-09-24 05:21:58 +0000692
693 def setAttribute(self, attname, value):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000694 attr = self.getAttributeNode(attname)
695 if attr is None:
696 attr = Attr(attname)
697 # for performance
698 d = attr.__dict__
699 d["value"] = d["nodeValue"] = value
700 d["ownerDocument"] = self.ownerDocument
701 self.setAttributeNode(attr)
702 elif value != attr.value:
703 d = attr.__dict__
704 d["value"] = d["nodeValue"] = value
705 if attr.isId:
706 _clear_id_cache(self)
Fred Drake55c38192000-06-29 19:39:57 +0000707
Fred Drake1f549022000-09-24 05:21:58 +0000708 def setAttributeNS(self, namespaceURI, qualifiedName, value):
709 prefix, localname = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000710 attr = self.getAttributeNodeNS(namespaceURI, localname)
711 if attr is None:
712 # for performance
713 attr = Attr(qualifiedName, namespaceURI, localname, prefix)
714 d = attr.__dict__
715 d["prefix"] = prefix
716 d["nodeName"] = qualifiedName
717 d["value"] = d["nodeValue"] = value
718 d["ownerDocument"] = self.ownerDocument
719 self.setAttributeNode(attr)
720 else:
721 d = attr.__dict__
722 if value != attr.value:
723 d["value"] = d["nodeValue"] = value
724 if attr.isId:
725 _clear_id_cache(self)
726 if attr.prefix != prefix:
727 d["prefix"] = prefix
728 d["nodeName"] = qualifiedName
Fred Drake55c38192000-06-29 19:39:57 +0000729
Fred Drake1f549022000-09-24 05:21:58 +0000730 def getAttributeNode(self, attrname):
731 return self._attrs.get(attrname)
Paul Prescod73678da2000-07-01 04:58:47 +0000732
Fred Drake1f549022000-09-24 05:21:58 +0000733 def getAttributeNodeNS(self, namespaceURI, localName):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000734 return self._attrsNS.get((namespaceURI, localName))
Paul Prescod73678da2000-07-01 04:58:47 +0000735
Fred Drake1f549022000-09-24 05:21:58 +0000736 def setAttributeNode(self, attr):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000737 if attr.ownerElement not in (None, self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000738 raise xml.dom.InuseAttributeErr("attribute node already owned")
Martin v. Löwis787354c2003-01-25 15:28:29 +0000739 old1 = self._attrs.get(attr.name, None)
740 if old1 is not None:
741 self.removeAttributeNode(old1)
742 old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None)
743 if old2 is not None and old2 is not old1:
744 self.removeAttributeNode(old2)
745 _set_attribute_node(self, attr)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000746
Martin v. Löwis787354c2003-01-25 15:28:29 +0000747 if old1 is not attr:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000748 # It might have already been part of this node, in which case
749 # it doesn't represent a change, and should not be returned.
Martin v. Löwis787354c2003-01-25 15:28:29 +0000750 return old1
751 if old2 is not attr:
752 return old2
Fred Drake55c38192000-06-29 19:39:57 +0000753
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000754 setAttributeNodeNS = setAttributeNode
755
Fred Drake1f549022000-09-24 05:21:58 +0000756 def removeAttribute(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000757 try:
758 attr = self._attrs[name]
759 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000760 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000761 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000762
Fred Drake1f549022000-09-24 05:21:58 +0000763 def removeAttributeNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000764 try:
765 attr = self._attrsNS[(namespaceURI, localName)]
766 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000767 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000768 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000769
Fred Drake1f549022000-09-24 05:21:58 +0000770 def removeAttributeNode(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000771 if node is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000772 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000773 try:
774 self._attrs[node.name]
775 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000776 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000777 _clear_id_cache(self)
Paul Prescod73678da2000-07-01 04:58:47 +0000778 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000779 # Restore this since the node is still useful and otherwise
780 # unlinked
781 node.ownerDocument = self.ownerDocument
Fred Drake16f63292000-10-23 18:09:50 +0000782
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000783 removeAttributeNodeNS = removeAttributeNode
784
Martin v. Löwis156c3372000-12-28 18:40:56 +0000785 def hasAttribute(self, name):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000786 return name in self._attrs
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000787
Martin v. Löwis156c3372000-12-28 18:40:56 +0000788 def hasAttributeNS(self, namespaceURI, localName):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000789 return (namespaceURI, localName) in self._attrsNS
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000790
Fred Drake1f549022000-09-24 05:21:58 +0000791 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000792 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000793
Fred Drake1f549022000-09-24 05:21:58 +0000794 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000795 return _get_elements_by_tagName_ns_helper(
796 self, namespaceURI, localName, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000797
Fred Drake1f549022000-09-24 05:21:58 +0000798 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000799 return "<DOM Element: %s at %#x>" % (self.tagName, id(self))
Fred Drake55c38192000-06-29 19:39:57 +0000800
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000801 def writexml(self, writer, indent="", addindent="", newl=""):
802 # indent = current indentation
803 # addindent = indentation to add to higher levels
804 # newl = newline string
805 writer.write(indent+"<" + self.tagName)
Fred Drake16f63292000-10-23 18:09:50 +0000806
Fred Drake4ccf4a12000-11-21 22:02:22 +0000807 attrs = self._get_attributes()
Brett Cannon861fd6f2007-02-21 22:05:37 +0000808 a_names = sorted(attrs.keys())
Fred Drake55c38192000-06-29 19:39:57 +0000809
810 for a_name in a_names:
Fred Drake1f549022000-09-24 05:21:58 +0000811 writer.write(" %s=\"" % a_name)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000812 _write_data(writer, attrs[a_name].value)
Fred Drake55c38192000-06-29 19:39:57 +0000813 writer.write("\"")
814 if self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000815 writer.write(">%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000816 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000817 node.writexml(writer,indent+addindent,addindent,newl)
818 writer.write("%s</%s>%s" % (indent,self.tagName,newl))
Fred Drake55c38192000-06-29 19:39:57 +0000819 else:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000820 writer.write("/>%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000821
Fred Drake1f549022000-09-24 05:21:58 +0000822 def _get_attributes(self):
Fred Drake2998a552001-12-06 18:27:48 +0000823 return NamedNodeMap(self._attrs, self._attrsNS, self)
Fred Drake55c38192000-06-29 19:39:57 +0000824
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000825 def hasAttributes(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000826 if self._attrs:
827 return True
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000828 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000829 return False
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000830
Martin v. Löwis787354c2003-01-25 15:28:29 +0000831 # DOM Level 3 attributes, based on the 22 Oct 2002 draft
832
833 def setIdAttribute(self, name):
834 idAttr = self.getAttributeNode(name)
835 self.setIdAttributeNode(idAttr)
836
837 def setIdAttributeNS(self, namespaceURI, localName):
838 idAttr = self.getAttributeNodeNS(namespaceURI, localName)
839 self.setIdAttributeNode(idAttr)
840
841 def setIdAttributeNode(self, idAttr):
842 if idAttr is None or not self.isSameNode(idAttr.ownerElement):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000843 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000844 if _get_containing_entref(self) is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000845 raise xml.dom.NoModificationAllowedErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000846 if not idAttr._is_id:
847 idAttr.__dict__['_is_id'] = True
848 self._magic_id_nodes += 1
849 self.ownerDocument._magic_id_count += 1
850 _clear_id_cache(self)
851
852defproperty(Element, "attributes",
853 doc="NamedNodeMap of attributes on the element.")
854defproperty(Element, "localName",
855 doc="Namespace-local name of this element.")
856
857
858def _set_attribute_node(element, attr):
859 _clear_id_cache(element)
860 element._attrs[attr.name] = attr
861 element._attrsNS[(attr.namespaceURI, attr.localName)] = attr
862
863 # This creates a circular reference, but Element.unlink()
864 # breaks the cycle since the references to the attribute
865 # dictionaries are tossed.
866 attr.__dict__['ownerElement'] = element
867
868
869class Childless:
870 """Mixin that makes childless-ness easy to implement and avoids
871 the complexity of the Node methods that deal with children.
872 """
873
Fred Drake4ccf4a12000-11-21 22:02:22 +0000874 attributes = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000875 childNodes = EmptyNodeList()
876 firstChild = None
877 lastChild = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000878
Martin v. Löwis787354c2003-01-25 15:28:29 +0000879 def _get_firstChild(self):
880 return None
Fred Drake55c38192000-06-29 19:39:57 +0000881
Martin v. Löwis787354c2003-01-25 15:28:29 +0000882 def _get_lastChild(self):
883 return None
Fred Drake1f549022000-09-24 05:21:58 +0000884
Martin v. Löwis787354c2003-01-25 15:28:29 +0000885 def appendChild(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000886 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000887 self.nodeName + " nodes cannot have children")
888
889 def hasChildNodes(self):
890 return False
891
892 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000893 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000894 self.nodeName + " nodes do not have children")
895
896 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000897 raise xml.dom.NotFoundErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000898 self.nodeName + " nodes do not have children")
899
900 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000901 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000902 self.nodeName + " nodes do not have children")
903
904
905class ProcessingInstruction(Childless, Node):
Fred Drake1f549022000-09-24 05:21:58 +0000906 nodeType = Node.PROCESSING_INSTRUCTION_NODE
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000907
Fred Drake1f549022000-09-24 05:21:58 +0000908 def __init__(self, target, data):
Fred Drake55c38192000-06-29 19:39:57 +0000909 self.target = self.nodeName = target
910 self.data = self.nodeValue = data
Fred Drake55c38192000-06-29 19:39:57 +0000911
Martin v. Löwis787354c2003-01-25 15:28:29 +0000912 def _get_data(self):
913 return self.data
914 def _set_data(self, value):
915 d = self.__dict__
916 d['data'] = d['nodeValue'] = value
917
918 def _get_target(self):
919 return self.target
920 def _set_target(self, value):
921 d = self.__dict__
922 d['target'] = d['nodeName'] = value
923
924 def __setattr__(self, name, value):
925 if name == "data" or name == "nodeValue":
926 self.__dict__['data'] = self.__dict__['nodeValue'] = value
927 elif name == "target" or name == "nodeName":
928 self.__dict__['target'] = self.__dict__['nodeName'] = value
929 else:
930 self.__dict__[name] = value
931
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000932 def writexml(self, writer, indent="", addindent="", newl=""):
933 writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000934
Martin v. Löwis787354c2003-01-25 15:28:29 +0000935
936class CharacterData(Childless, Node):
937 def _get_length(self):
938 return len(self.data)
939 __len__ = _get_length
940
941 def _get_data(self):
942 return self.__dict__['data']
943 def _set_data(self, data):
944 d = self.__dict__
945 d['data'] = d['nodeValue'] = data
946
947 _get_nodeValue = _get_data
948 _set_nodeValue = _set_data
949
950 def __setattr__(self, name, value):
951 if name == "data" or name == "nodeValue":
952 self.__dict__['data'] = self.__dict__['nodeValue'] = value
953 else:
954 self.__dict__[name] = value
Fred Drake87432f42001-04-04 14:09:46 +0000955
Fred Drake55c38192000-06-29 19:39:57 +0000956 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000957 data = self.data
958 if len(data) > 10:
Fred Drake1f549022000-09-24 05:21:58 +0000959 dotdotdot = "..."
Fred Drake55c38192000-06-29 19:39:57 +0000960 else:
Fred Drake1f549022000-09-24 05:21:58 +0000961 dotdotdot = ""
Fred Drake87432f42001-04-04 14:09:46 +0000962 return "<DOM %s node \"%s%s\">" % (
Martin v. Löwis787354c2003-01-25 15:28:29 +0000963 self.__class__.__name__, data[0:10], dotdotdot)
Fred Drake87432f42001-04-04 14:09:46 +0000964
965 def substringData(self, offset, count):
966 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000967 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000968 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000969 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +0000970 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000971 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000972 return self.data[offset:offset+count]
973
974 def appendData(self, arg):
975 self.data = self.data + arg
Fred Drake87432f42001-04-04 14:09:46 +0000976
977 def insertData(self, offset, arg):
978 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000979 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000980 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000981 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +0000982 if arg:
983 self.data = "%s%s%s" % (
984 self.data[:offset], arg, self.data[offset:])
Fred Drake87432f42001-04-04 14:09:46 +0000985
986 def deleteData(self, offset, count):
987 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000988 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000989 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000990 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +0000991 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000992 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000993 if count:
994 self.data = self.data[:offset] + self.data[offset+count:]
Fred Drake87432f42001-04-04 14:09:46 +0000995
996 def replaceData(self, offset, count, arg):
997 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000998 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +0000999 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001000 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001001 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001002 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001003 if count:
1004 self.data = "%s%s%s" % (
1005 self.data[:offset], arg, self.data[offset+count:])
Martin v. Löwis787354c2003-01-25 15:28:29 +00001006
1007defproperty(CharacterData, "length", doc="Length of the string data.")
1008
Fred Drake87432f42001-04-04 14:09:46 +00001009
1010class Text(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001011 # Make sure we don't add an instance __dict__ if we don't already
1012 # have one, at least when that's possible:
Martin v. Löwis995359c2003-01-26 08:59:32 +00001013 # XXX this does not work, CharacterData is an old-style class
1014 # __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001015
Fred Drake87432f42001-04-04 14:09:46 +00001016 nodeType = Node.TEXT_NODE
1017 nodeName = "#text"
1018 attributes = None
Fred Drake55c38192000-06-29 19:39:57 +00001019
Fred Drakef7cf40d2000-12-14 18:16:11 +00001020 def splitText(self, offset):
1021 if offset < 0 or offset > len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001022 raise xml.dom.IndexSizeErr("illegal offset value")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001023 newText = self.__class__()
1024 newText.data = self.data[offset:]
1025 newText.ownerDocument = self.ownerDocument
Fred Drakef7cf40d2000-12-14 18:16:11 +00001026 next = self.nextSibling
1027 if self.parentNode and self in self.parentNode.childNodes:
1028 if next is None:
1029 self.parentNode.appendChild(newText)
1030 else:
1031 self.parentNode.insertBefore(newText, next)
1032 self.data = self.data[:offset]
1033 return newText
1034
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001035 def writexml(self, writer, indent="", addindent="", newl=""):
1036 _write_data(writer, "%s%s%s"%(indent, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001037
Martin v. Löwis787354c2003-01-25 15:28:29 +00001038 # DOM Level 3 (WD 9 April 2002)
1039
1040 def _get_wholeText(self):
1041 L = [self.data]
1042 n = self.previousSibling
1043 while n is not None:
1044 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1045 L.insert(0, n.data)
1046 n = n.previousSibling
1047 else:
1048 break
1049 n = self.nextSibling
1050 while n is not None:
1051 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1052 L.append(n.data)
1053 n = n.nextSibling
1054 else:
1055 break
1056 return ''.join(L)
1057
1058 def replaceWholeText(self, content):
1059 # XXX This needs to be seriously changed if minidom ever
1060 # supports EntityReference nodes.
1061 parent = self.parentNode
1062 n = self.previousSibling
1063 while n is not None:
1064 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1065 next = n.previousSibling
1066 parent.removeChild(n)
1067 n = next
1068 else:
1069 break
1070 n = self.nextSibling
1071 if not content:
1072 parent.removeChild(self)
1073 while n is not None:
1074 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1075 next = n.nextSibling
1076 parent.removeChild(n)
1077 n = next
1078 else:
1079 break
1080 if content:
1081 d = self.__dict__
1082 d['data'] = content
1083 d['nodeValue'] = content
1084 return self
1085 else:
1086 return None
1087
1088 def _get_isWhitespaceInElementContent(self):
1089 if self.data.strip():
1090 return False
1091 elem = _get_containing_element(self)
1092 if elem is None:
1093 return False
1094 info = self.ownerDocument._get_elem_info(elem)
1095 if info is None:
1096 return False
1097 else:
1098 return info.isElementContent()
1099
1100defproperty(Text, "isWhitespaceInElementContent",
1101 doc="True iff this text node contains only whitespace"
1102 " and is in element content.")
1103defproperty(Text, "wholeText",
1104 doc="The text of all logically-adjacent text nodes.")
1105
1106
1107def _get_containing_element(node):
1108 c = node.parentNode
1109 while c is not None:
1110 if c.nodeType == Node.ELEMENT_NODE:
1111 return c
1112 c = c.parentNode
1113 return None
1114
1115def _get_containing_entref(node):
1116 c = node.parentNode
1117 while c is not None:
1118 if c.nodeType == Node.ENTITY_REFERENCE_NODE:
1119 return c
1120 c = c.parentNode
1121 return None
1122
1123
Alex Martelli0ee43512006-08-21 19:53:20 +00001124class Comment(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001125 nodeType = Node.COMMENT_NODE
1126 nodeName = "#comment"
1127
1128 def __init__(self, data):
1129 self.data = self.nodeValue = data
1130
1131 def writexml(self, writer, indent="", addindent="", newl=""):
1132 writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1133
Fred Drake87432f42001-04-04 14:09:46 +00001134
1135class CDATASection(Text):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001136 # Make sure we don't add an instance __dict__ if we don't already
1137 # have one, at least when that's possible:
Martin v. Löwis995359c2003-01-26 08:59:32 +00001138 # XXX this does not work, Text is an old-style class
1139 # __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001140
Fred Drake87432f42001-04-04 14:09:46 +00001141 nodeType = Node.CDATA_SECTION_NODE
1142 nodeName = "#cdata-section"
1143
1144 def writexml(self, writer, indent="", addindent="", newl=""):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001145 if self.data.find("]]>") >= 0:
1146 raise ValueError("']]>' not allowed in a CDATA section")
Guido van Rossum5b5e0b92001-09-19 13:28:25 +00001147 writer.write("<![CDATA[%s]]>" % self.data)
Fred Drake87432f42001-04-04 14:09:46 +00001148
1149
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001150class ReadOnlySequentialNamedNodeMap(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001151 __slots__ = '_seq',
1152
1153 def __init__(self, seq=()):
1154 # seq should be a list or tuple
1155 self._seq = seq
1156
1157 def __len__(self):
1158 return len(self._seq)
1159
1160 def _get_length(self):
1161 return len(self._seq)
1162
1163 def getNamedItem(self, name):
1164 for n in self._seq:
1165 if n.nodeName == name:
1166 return n
1167
1168 def getNamedItemNS(self, namespaceURI, localName):
1169 for n in self._seq:
1170 if n.namespaceURI == namespaceURI and n.localName == localName:
1171 return n
1172
1173 def __getitem__(self, name_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001174 if isinstance(name_or_tuple, tuple):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001175 node = self.getNamedItemNS(*name_or_tuple)
1176 else:
1177 node = self.getNamedItem(name_or_tuple)
1178 if node is None:
1179 raise KeyError, name_or_tuple
1180 return node
1181
1182 def item(self, index):
1183 if index < 0:
1184 return None
1185 try:
1186 return self._seq[index]
1187 except IndexError:
1188 return None
1189
1190 def removeNamedItem(self, name):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001191 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001192 "NamedNodeMap instance is read-only")
1193
1194 def removeNamedItemNS(self, namespaceURI, localName):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001195 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001196 "NamedNodeMap instance is read-only")
1197
1198 def setNamedItem(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001199 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001200 "NamedNodeMap instance is read-only")
1201
1202 def setNamedItemNS(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001203 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001204 "NamedNodeMap instance is read-only")
1205
1206 def __getstate__(self):
1207 return [self._seq]
1208
1209 def __setstate__(self, state):
1210 self._seq = state[0]
1211
1212defproperty(ReadOnlySequentialNamedNodeMap, "length",
1213 doc="Number of entries in the NamedNodeMap.")
Paul Prescod73678da2000-07-01 04:58:47 +00001214
Fred Drakef7cf40d2000-12-14 18:16:11 +00001215
Martin v. Löwis787354c2003-01-25 15:28:29 +00001216class Identified:
1217 """Mix-in class that supports the publicId and systemId attributes."""
1218
Martin v. Löwis995359c2003-01-26 08:59:32 +00001219 # XXX this does not work, this is an old-style class
1220 # __slots__ = 'publicId', 'systemId'
Martin v. Löwis787354c2003-01-25 15:28:29 +00001221
1222 def _identified_mixin_init(self, publicId, systemId):
1223 self.publicId = publicId
1224 self.systemId = systemId
1225
1226 def _get_publicId(self):
1227 return self.publicId
1228
1229 def _get_systemId(self):
1230 return self.systemId
1231
1232class DocumentType(Identified, Childless, Node):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001233 nodeType = Node.DOCUMENT_TYPE_NODE
1234 nodeValue = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001235 name = None
1236 publicId = None
1237 systemId = None
Fred Drakedc806702001-04-05 14:41:30 +00001238 internalSubset = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001239
1240 def __init__(self, qualifiedName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001241 self.entities = ReadOnlySequentialNamedNodeMap()
1242 self.notations = ReadOnlySequentialNamedNodeMap()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001243 if qualifiedName:
1244 prefix, localname = _nssplit(qualifiedName)
1245 self.name = localname
Martin v. Löwis787354c2003-01-25 15:28:29 +00001246 self.nodeName = self.name
1247
1248 def _get_internalSubset(self):
1249 return self.internalSubset
1250
1251 def cloneNode(self, deep):
1252 if self.ownerDocument is None:
1253 # it's ok
1254 clone = DocumentType(None)
1255 clone.name = self.name
1256 clone.nodeName = self.name
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001257 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001258 if deep:
1259 clone.entities._seq = []
1260 clone.notations._seq = []
1261 for n in self.notations._seq:
1262 notation = Notation(n.nodeName, n.publicId, n.systemId)
1263 clone.notations._seq.append(notation)
1264 n._call_user_data_handler(operation, n, notation)
1265 for e in self.entities._seq:
1266 entity = Entity(e.nodeName, e.publicId, e.systemId,
1267 e.notationName)
1268 entity.actualEncoding = e.actualEncoding
1269 entity.encoding = e.encoding
1270 entity.version = e.version
1271 clone.entities._seq.append(entity)
1272 e._call_user_data_handler(operation, n, entity)
1273 self._call_user_data_handler(operation, self, clone)
1274 return clone
1275 else:
1276 return None
1277
1278 def writexml(self, writer, indent="", addindent="", newl=""):
1279 writer.write("<!DOCTYPE ")
1280 writer.write(self.name)
1281 if self.publicId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001282 writer.write("%s PUBLIC '%s'%s '%s'"
1283 % (newl, self.publicId, newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001284 elif self.systemId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001285 writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001286 if self.internalSubset is not None:
1287 writer.write(" [")
1288 writer.write(self.internalSubset)
1289 writer.write("]")
Georg Brandl175a7dc2005-08-25 22:02:43 +00001290 writer.write(">"+newl)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001291
1292class Entity(Identified, Node):
1293 attributes = None
1294 nodeType = Node.ENTITY_NODE
1295 nodeValue = None
1296
1297 actualEncoding = None
1298 encoding = None
1299 version = None
1300
1301 def __init__(self, name, publicId, systemId, notation):
1302 self.nodeName = name
1303 self.notationName = notation
1304 self.childNodes = NodeList()
1305 self._identified_mixin_init(publicId, systemId)
1306
1307 def _get_actualEncoding(self):
1308 return self.actualEncoding
1309
1310 def _get_encoding(self):
1311 return self.encoding
1312
1313 def _get_version(self):
1314 return self.version
1315
1316 def appendChild(self, newChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001317 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001318 "cannot append children to an entity node")
1319
1320 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001321 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001322 "cannot insert children below an entity node")
1323
1324 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001325 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001326 "cannot remove children from an entity node")
1327
1328 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001329 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001330 "cannot replace children of an entity node")
1331
1332class Notation(Identified, Childless, Node):
1333 nodeType = Node.NOTATION_NODE
1334 nodeValue = None
1335
1336 def __init__(self, name, publicId, systemId):
1337 self.nodeName = name
1338 self._identified_mixin_init(publicId, systemId)
Fred Drakef7cf40d2000-12-14 18:16:11 +00001339
1340
Martin v. Löwis787354c2003-01-25 15:28:29 +00001341class DOMImplementation(DOMImplementationLS):
1342 _features = [("core", "1.0"),
1343 ("core", "2.0"),
1344 ("core", "3.0"),
1345 ("core", None),
1346 ("xml", "1.0"),
1347 ("xml", "2.0"),
1348 ("xml", "3.0"),
1349 ("xml", None),
1350 ("ls-load", "3.0"),
1351 ("ls-load", None),
1352 ]
1353
Fred Drakef7cf40d2000-12-14 18:16:11 +00001354 def hasFeature(self, feature, version):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001355 if version == "":
1356 version = None
1357 return (feature.lower(), version) in self._features
Fred Drakef7cf40d2000-12-14 18:16:11 +00001358
1359 def createDocument(self, namespaceURI, qualifiedName, doctype):
1360 if doctype and doctype.parentNode is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001361 raise xml.dom.WrongDocumentErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001362 "doctype object owned by another DOM tree")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001363 doc = self._create_document()
1364
1365 add_root_element = not (namespaceURI is None
1366 and qualifiedName is None
1367 and doctype is None)
1368
1369 if not qualifiedName and add_root_element:
Martin v. Löwisb417be22001-02-06 01:16:06 +00001370 # The spec is unclear what to raise here; SyntaxErr
1371 # would be the other obvious candidate. Since Xerces raises
1372 # InvalidCharacterErr, and since SyntaxErr is not listed
1373 # for createDocument, that seems to be the better choice.
1374 # XXX: need to check for illegal characters here and in
1375 # createElement.
Martin v. Löwis787354c2003-01-25 15:28:29 +00001376
1377 # DOM Level III clears this up when talking about the return value
1378 # of this function. If namespaceURI, qName and DocType are
1379 # Null the document is returned without a document element
1380 # Otherwise if doctype or namespaceURI are not None
1381 # Then we go back to the above problem
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001382 raise xml.dom.InvalidCharacterErr("Element with no name")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001383
1384 if add_root_element:
1385 prefix, localname = _nssplit(qualifiedName)
1386 if prefix == "xml" \
1387 and namespaceURI != "http://www.w3.org/XML/1998/namespace":
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001388 raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001389 if prefix and not namespaceURI:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001390 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001391 "illegal use of prefix without namespaces")
1392 element = doc.createElementNS(namespaceURI, qualifiedName)
1393 if doctype:
1394 doc.appendChild(doctype)
1395 doc.appendChild(element)
1396
1397 if doctype:
1398 doctype.parentNode = doctype.ownerDocument = doc
1399
Fred Drakef7cf40d2000-12-14 18:16:11 +00001400 doc.doctype = doctype
1401 doc.implementation = self
1402 return doc
1403
1404 def createDocumentType(self, qualifiedName, publicId, systemId):
1405 doctype = DocumentType(qualifiedName)
1406 doctype.publicId = publicId
1407 doctype.systemId = systemId
1408 return doctype
1409
Martin v. Löwis787354c2003-01-25 15:28:29 +00001410 # DOM Level 3 (WD 9 April 2002)
1411
1412 def getInterface(self, feature):
1413 if self.hasFeature(feature, None):
1414 return self
1415 else:
1416 return None
1417
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001418 # internal
Martin v. Löwis787354c2003-01-25 15:28:29 +00001419 def _create_document(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001420 return Document()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001421
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001422class ElementInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001423 """Object that represents content-model information for an element.
1424
1425 This implementation is not expected to be used in practice; DOM
1426 builders should provide implementations which do the right thing
1427 using information available to it.
1428
1429 """
1430
1431 __slots__ = 'tagName',
1432
1433 def __init__(self, name):
1434 self.tagName = name
1435
1436 def getAttributeType(self, aname):
1437 return _no_type
1438
1439 def getAttributeTypeNS(self, namespaceURI, localName):
1440 return _no_type
1441
1442 def isElementContent(self):
1443 return False
1444
1445 def isEmpty(self):
1446 """Returns true iff this element is declared to have an EMPTY
1447 content model."""
1448 return False
1449
1450 def isId(self, aname):
1451 """Returns true iff the named attribte is a DTD-style ID."""
1452 return False
1453
1454 def isIdNS(self, namespaceURI, localName):
1455 """Returns true iff the identified attribute is a DTD-style ID."""
1456 return False
1457
1458 def __getstate__(self):
1459 return self.tagName
1460
1461 def __setstate__(self, state):
1462 self.tagName = state
1463
1464def _clear_id_cache(node):
1465 if node.nodeType == Node.DOCUMENT_NODE:
1466 node._id_cache.clear()
1467 node._id_search_stack = None
1468 elif _in_document(node):
1469 node.ownerDocument._id_cache.clear()
1470 node.ownerDocument._id_search_stack= None
1471
1472class Document(Node, DocumentLS):
1473 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
1474 Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE)
1475
Fred Drake1f549022000-09-24 05:21:58 +00001476 nodeType = Node.DOCUMENT_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +00001477 nodeName = "#document"
1478 nodeValue = None
1479 attributes = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001480 doctype = None
1481 parentNode = None
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001482 previousSibling = nextSibling = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001483
1484 implementation = DOMImplementation()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001485
1486 # Document attributes from Level 3 (WD 9 April 2002)
1487
1488 actualEncoding = None
1489 encoding = None
1490 standalone = None
1491 version = None
1492 strictErrorChecking = False
1493 errorHandler = None
1494 documentURI = None
1495
1496 _magic_id_count = 0
1497
1498 def __init__(self):
1499 self.childNodes = NodeList()
1500 # mapping of (namespaceURI, localName) -> ElementInfo
1501 # and tagName -> ElementInfo
1502 self._elem_info = {}
1503 self._id_cache = {}
1504 self._id_search_stack = None
1505
1506 def _get_elem_info(self, element):
1507 if element.namespaceURI:
1508 key = element.namespaceURI, element.localName
1509 else:
1510 key = element.tagName
1511 return self._elem_info.get(key)
1512
1513 def _get_actualEncoding(self):
1514 return self.actualEncoding
1515
1516 def _get_doctype(self):
1517 return self.doctype
1518
1519 def _get_documentURI(self):
1520 return self.documentURI
1521
1522 def _get_encoding(self):
1523 return self.encoding
1524
1525 def _get_errorHandler(self):
1526 return self.errorHandler
1527
1528 def _get_standalone(self):
1529 return self.standalone
1530
1531 def _get_strictErrorChecking(self):
1532 return self.strictErrorChecking
1533
1534 def _get_version(self):
1535 return self.version
Fred Drake55c38192000-06-29 19:39:57 +00001536
Fred Drake1f549022000-09-24 05:21:58 +00001537 def appendChild(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001538 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001539 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001540 "%s cannot be child of %s" % (repr(node), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001541 if node.parentNode is not None:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001542 # This needs to be done before the next test since this
1543 # may *be* the document element, in which case it should
1544 # end up re-ordered to the end.
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001545 node.parentNode.removeChild(node)
1546
Fred Drakef7cf40d2000-12-14 18:16:11 +00001547 if node.nodeType == Node.ELEMENT_NODE \
1548 and self._get_documentElement():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001549 raise xml.dom.HierarchyRequestErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001550 "two document elements disallowed")
Fred Drake4ccf4a12000-11-21 22:02:22 +00001551 return Node.appendChild(self, node)
Paul Prescod73678da2000-07-01 04:58:47 +00001552
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001553 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001554 try:
1555 self.childNodes.remove(oldChild)
1556 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001557 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001558 oldChild.nextSibling = oldChild.previousSibling = None
1559 oldChild.parentNode = None
1560 if self.documentElement is oldChild:
1561 self.documentElement = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +00001562
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001563 return oldChild
1564
Fred Drakef7cf40d2000-12-14 18:16:11 +00001565 def _get_documentElement(self):
1566 for node in self.childNodes:
1567 if node.nodeType == Node.ELEMENT_NODE:
1568 return node
1569
1570 def unlink(self):
1571 if self.doctype is not None:
1572 self.doctype.unlink()
1573 self.doctype = None
1574 Node.unlink(self)
1575
Martin v. Löwis787354c2003-01-25 15:28:29 +00001576 def cloneNode(self, deep):
1577 if not deep:
1578 return None
1579 clone = self.implementation.createDocument(None, None, None)
1580 clone.encoding = self.encoding
1581 clone.standalone = self.standalone
1582 clone.version = self.version
1583 for n in self.childNodes:
1584 childclone = _clone_node(n, deep, clone)
1585 assert childclone.ownerDocument.isSameNode(clone)
1586 clone.childNodes.append(childclone)
1587 if childclone.nodeType == Node.DOCUMENT_NODE:
1588 assert clone.documentElement is None
1589 elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE:
1590 assert clone.doctype is None
1591 clone.doctype = childclone
1592 childclone.parentNode = clone
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001593 self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED,
Martin v. Löwis787354c2003-01-25 15:28:29 +00001594 self, clone)
1595 return clone
1596
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001597 def createDocumentFragment(self):
1598 d = DocumentFragment()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001599 d.ownerDocument = self
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001600 return d
Fred Drake55c38192000-06-29 19:39:57 +00001601
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001602 def createElement(self, tagName):
1603 e = Element(tagName)
1604 e.ownerDocument = self
1605 return e
Fred Drake55c38192000-06-29 19:39:57 +00001606
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001607 def createTextNode(self, data):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001608 if not isinstance(data, StringTypes):
1609 raise TypeError, "node contents must be a string"
1610 t = Text()
1611 t.data = data
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001612 t.ownerDocument = self
1613 return t
Fred Drake55c38192000-06-29 19:39:57 +00001614
Fred Drake87432f42001-04-04 14:09:46 +00001615 def createCDATASection(self, data):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001616 if not isinstance(data, StringTypes):
1617 raise TypeError, "node contents must be a string"
1618 c = CDATASection()
1619 c.data = data
Fred Drake87432f42001-04-04 14:09:46 +00001620 c.ownerDocument = self
1621 return c
1622
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001623 def createComment(self, data):
1624 c = Comment(data)
1625 c.ownerDocument = self
1626 return c
Fred Drake55c38192000-06-29 19:39:57 +00001627
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001628 def createProcessingInstruction(self, target, data):
1629 p = ProcessingInstruction(target, data)
1630 p.ownerDocument = self
1631 return p
1632
1633 def createAttribute(self, qName):
1634 a = Attr(qName)
1635 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001636 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001637 return a
Fred Drake55c38192000-06-29 19:39:57 +00001638
1639 def createElementNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001640 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001641 e = Element(qualifiedName, namespaceURI, prefix)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001642 e.ownerDocument = self
1643 return e
Fred Drake55c38192000-06-29 19:39:57 +00001644
1645 def createAttributeNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001646 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001647 a = Attr(qualifiedName, namespaceURI, localName, prefix)
1648 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001649 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001650 return a
Fred Drake55c38192000-06-29 19:39:57 +00001651
Martin v. Löwis787354c2003-01-25 15:28:29 +00001652 # A couple of implementation-specific helpers to create node types
1653 # not supported by the W3C DOM specs:
1654
1655 def _create_entity(self, name, publicId, systemId, notationName):
1656 e = Entity(name, publicId, systemId, notationName)
1657 e.ownerDocument = self
1658 return e
1659
1660 def _create_notation(self, name, publicId, systemId):
1661 n = Notation(name, publicId, systemId)
1662 n.ownerDocument = self
1663 return n
1664
1665 def getElementById(self, id):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +00001666 if id in self._id_cache:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001667 return self._id_cache[id]
1668 if not (self._elem_info or self._magic_id_count):
1669 return None
1670
1671 stack = self._id_search_stack
1672 if stack is None:
1673 # we never searched before, or the cache has been cleared
1674 stack = [self.documentElement]
1675 self._id_search_stack = stack
1676 elif not stack:
1677 # Previous search was completed and cache is still valid;
1678 # no matching node.
1679 return None
1680
1681 result = None
1682 while stack:
1683 node = stack.pop()
1684 # add child elements to stack for continued searching
1685 stack.extend([child for child in node.childNodes
1686 if child.nodeType in _nodeTypes_with_children])
1687 # check this node
1688 info = self._get_elem_info(node)
1689 if info:
1690 # We have to process all ID attributes before
1691 # returning in order to get all the attributes set to
1692 # be IDs using Element.setIdAttribute*().
1693 for attr in node.attributes.values():
1694 if attr.namespaceURI:
1695 if info.isIdNS(attr.namespaceURI, attr.localName):
1696 self._id_cache[attr.value] = node
1697 if attr.value == id:
1698 result = node
1699 elif not node._magic_id_nodes:
1700 break
1701 elif info.isId(attr.name):
1702 self._id_cache[attr.value] = node
1703 if attr.value == id:
1704 result = node
1705 elif not node._magic_id_nodes:
1706 break
1707 elif attr._is_id:
1708 self._id_cache[attr.value] = node
1709 if attr.value == id:
1710 result = node
1711 elif node._magic_id_nodes == 1:
1712 break
1713 elif node._magic_id_nodes:
1714 for attr in node.attributes.values():
1715 if attr._is_id:
1716 self._id_cache[attr.value] = node
1717 if attr.value == id:
1718 result = node
1719 if result is not None:
1720 break
1721 return result
1722
Fred Drake1f549022000-09-24 05:21:58 +00001723 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001724 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drakefbe7b4f2001-07-04 06:25:53 +00001725
1726 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001727 return _get_elements_by_tagName_ns_helper(
1728 self, namespaceURI, localName, NodeList())
1729
1730 def isSupported(self, feature, version):
1731 return self.implementation.hasFeature(feature, version)
1732
1733 def importNode(self, node, deep):
1734 if node.nodeType == Node.DOCUMENT_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001735 raise xml.dom.NotSupportedErr("cannot import document nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001736 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001737 raise xml.dom.NotSupportedErr("cannot import document type nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001738 return _clone_node(node, deep, self)
Fred Drake55c38192000-06-29 19:39:57 +00001739
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001740 def writexml(self, writer, indent="", addindent="", newl="",
1741 encoding = None):
1742 if encoding is None:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001743 writer.write('<?xml version="1.0" ?>'+newl)
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001744 else:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001745 writer.write('<?xml version="1.0" encoding="%s"?>%s' % (encoding, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001746 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001747 node.writexml(writer, indent, addindent, newl)
Fred Drake55c38192000-06-29 19:39:57 +00001748
Martin v. Löwis787354c2003-01-25 15:28:29 +00001749 # DOM Level 3 (WD 9 April 2002)
1750
1751 def renameNode(self, n, namespaceURI, name):
1752 if n.ownerDocument is not self:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001753 raise xml.dom.WrongDocumentErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001754 "cannot rename nodes from other documents;\n"
1755 "expected %s,\nfound %s" % (self, n.ownerDocument))
1756 if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001757 raise xml.dom.NotSupportedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001758 "renameNode() only applies to element and attribute nodes")
1759 if namespaceURI != EMPTY_NAMESPACE:
1760 if ':' in name:
1761 prefix, localName = name.split(':', 1)
1762 if ( prefix == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001763 and namespaceURI != xml.dom.XMLNS_NAMESPACE):
1764 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001765 "illegal use of 'xmlns' prefix")
1766 else:
1767 if ( name == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001768 and namespaceURI != xml.dom.XMLNS_NAMESPACE
Martin v. Löwis787354c2003-01-25 15:28:29 +00001769 and n.nodeType == Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001770 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001771 "illegal use of the 'xmlns' attribute")
1772 prefix = None
1773 localName = name
1774 else:
1775 prefix = None
1776 localName = None
1777 if n.nodeType == Node.ATTRIBUTE_NODE:
1778 element = n.ownerElement
1779 if element is not None:
1780 is_id = n._is_id
1781 element.removeAttributeNode(n)
1782 else:
1783 element = None
1784 # avoid __setattr__
1785 d = n.__dict__
1786 d['prefix'] = prefix
1787 d['localName'] = localName
1788 d['namespaceURI'] = namespaceURI
1789 d['nodeName'] = name
1790 if n.nodeType == Node.ELEMENT_NODE:
1791 d['tagName'] = name
1792 else:
1793 # attribute node
1794 d['name'] = name
1795 if element is not None:
1796 element.setAttributeNode(n)
1797 if is_id:
1798 element.setIdAttributeNode(n)
1799 # It's not clear from a semantic perspective whether we should
1800 # call the user data handlers for the NODE_RENAMED event since
1801 # we're re-using the existing node. The draft spec has been
1802 # interpreted as meaning "no, don't call the handler unless a
1803 # new node is created."
1804 return n
1805
1806defproperty(Document, "documentElement",
1807 doc="Top-level element of this document.")
1808
1809
1810def _clone_node(node, deep, newOwnerDocument):
1811 """
1812 Clone a node and give it the new owner document.
1813 Called by Node.cloneNode and Document.importNode
1814 """
1815 if node.ownerDocument.isSameNode(newOwnerDocument):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001816 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001817 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001818 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001819 if node.nodeType == Node.ELEMENT_NODE:
1820 clone = newOwnerDocument.createElementNS(node.namespaceURI,
1821 node.nodeName)
1822 for attr in node.attributes.values():
1823 clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
1824 a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)
1825 a.specified = attr.specified
1826
1827 if deep:
1828 for child in node.childNodes:
1829 c = _clone_node(child, deep, newOwnerDocument)
1830 clone.appendChild(c)
1831
1832 elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
1833 clone = newOwnerDocument.createDocumentFragment()
1834 if deep:
1835 for child in node.childNodes:
1836 c = _clone_node(child, deep, newOwnerDocument)
1837 clone.appendChild(c)
1838
1839 elif node.nodeType == Node.TEXT_NODE:
1840 clone = newOwnerDocument.createTextNode(node.data)
1841 elif node.nodeType == Node.CDATA_SECTION_NODE:
1842 clone = newOwnerDocument.createCDATASection(node.data)
1843 elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
1844 clone = newOwnerDocument.createProcessingInstruction(node.target,
1845 node.data)
1846 elif node.nodeType == Node.COMMENT_NODE:
1847 clone = newOwnerDocument.createComment(node.data)
1848 elif node.nodeType == Node.ATTRIBUTE_NODE:
1849 clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
1850 node.nodeName)
1851 clone.specified = True
1852 clone.value = node.value
1853 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
1854 assert node.ownerDocument is not newOwnerDocument
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001855 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001856 clone = newOwnerDocument.implementation.createDocumentType(
1857 node.name, node.publicId, node.systemId)
1858 clone.ownerDocument = newOwnerDocument
1859 if deep:
1860 clone.entities._seq = []
1861 clone.notations._seq = []
1862 for n in node.notations._seq:
1863 notation = Notation(n.nodeName, n.publicId, n.systemId)
1864 notation.ownerDocument = newOwnerDocument
1865 clone.notations._seq.append(notation)
1866 if hasattr(n, '_call_user_data_handler'):
1867 n._call_user_data_handler(operation, n, notation)
1868 for e in node.entities._seq:
1869 entity = Entity(e.nodeName, e.publicId, e.systemId,
1870 e.notationName)
1871 entity.actualEncoding = e.actualEncoding
1872 entity.encoding = e.encoding
1873 entity.version = e.version
1874 entity.ownerDocument = newOwnerDocument
1875 clone.entities._seq.append(entity)
1876 if hasattr(e, '_call_user_data_handler'):
1877 e._call_user_data_handler(operation, n, entity)
1878 else:
1879 # Note the cloning of Document and DocumentType nodes is
1880 # implemenetation specific. minidom handles those cases
1881 # directly in the cloneNode() methods.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001882 raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001883
1884 # Check for _call_user_data_handler() since this could conceivably
1885 # used with other DOM implementations (one of the FourThought
1886 # DOMs, perhaps?).
1887 if hasattr(node, '_call_user_data_handler'):
1888 node._call_user_data_handler(operation, node, clone)
1889 return clone
1890
1891
1892def _nssplit(qualifiedName):
1893 fields = qualifiedName.split(':', 1)
1894 if len(fields) == 2:
1895 return fields
1896 else:
1897 return (None, fields[0])
1898
1899
Fred Drake4ccf4a12000-11-21 22:02:22 +00001900def _get_StringIO():
Fred Drakef7cf40d2000-12-14 18:16:11 +00001901 # we can't use cStringIO since it doesn't support Unicode strings
1902 from StringIO import StringIO
Fred Drake4ccf4a12000-11-21 22:02:22 +00001903 return StringIO()
1904
Martin v. Löwis787354c2003-01-25 15:28:29 +00001905def _do_pulldom_parse(func, args, kwargs):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001906 events = func(*args, **kwargs)
Fred Drake1f549022000-09-24 05:21:58 +00001907 toktype, rootNode = events.getEvent()
1908 events.expandNode(rootNode)
Martin v. Löwisb417be22001-02-06 01:16:06 +00001909 events.clear()
Fred Drake55c38192000-06-29 19:39:57 +00001910 return rootNode
1911
Martin v. Löwis787354c2003-01-25 15:28:29 +00001912def parse(file, parser=None, bufsize=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001913 """Parse a file into a DOM by filename or file object."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001914 if parser is None and not bufsize:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001915 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001916 return expatbuilder.parse(file)
1917 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001918 from xml.dom import pulldom
Raymond Hettingerff41c482003-04-06 09:01:11 +00001919 return _do_pulldom_parse(pulldom.parse, (file,),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001920 {'parser': parser, 'bufsize': bufsize})
Fred Drake55c38192000-06-29 19:39:57 +00001921
Martin v. Löwis787354c2003-01-25 15:28:29 +00001922def parseString(string, parser=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001923 """Parse a file into a DOM from a string."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001924 if parser is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001925 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001926 return expatbuilder.parseString(string)
1927 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001928 from xml.dom import pulldom
Martin v. Löwis787354c2003-01-25 15:28:29 +00001929 return _do_pulldom_parse(pulldom.parseString, (string,),
1930 {'parser': parser})
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001931
Martin v. Löwis787354c2003-01-25 15:28:29 +00001932def getDOMImplementation(features=None):
1933 if features:
1934 if isinstance(features, StringTypes):
1935 features = domreg._parse_feature_string(features)
1936 for f, v in features:
1937 if not Document.implementation.hasFeature(f, v):
1938 return None
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001939 return Document.implementation