blob: f23ad053333b53005612cbf88fbefc1b5a0e2954 [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."
Georg Brandlb9cd72a2010-10-15 17:58:45 +0000304 if data:
305 data = data.replace("&", "&amp;").replace("<", "&lt;"). \
306 replace("\"", "&quot;").replace(">", "&gt;")
307 writer.write(data)
Fred Drake55c38192000-06-29 19:39:57 +0000308
Martin v. Löwis787354c2003-01-25 15:28:29 +0000309def _get_elements_by_tagName_helper(parent, name, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000310 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000311 if node.nodeType == Node.ELEMENT_NODE and \
312 (name == "*" or node.tagName == name):
313 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000314 _get_elements_by_tagName_helper(node, name, rc)
Fred Drake55c38192000-06-29 19:39:57 +0000315 return rc
316
Martin v. Löwis787354c2003-01-25 15:28:29 +0000317def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc):
Fred Drake55c38192000-06-29 19:39:57 +0000318 for node in parent.childNodes:
Fred Drake1f549022000-09-24 05:21:58 +0000319 if node.nodeType == Node.ELEMENT_NODE:
Martin v. Löwised525fb2001-06-03 14:06:42 +0000320 if ((localName == "*" or node.localName == localName) and
Fred Drake1f549022000-09-24 05:21:58 +0000321 (nsURI == "*" or node.namespaceURI == nsURI)):
322 rc.append(node)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000323 _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000324 return rc
Fred Drake55c38192000-06-29 19:39:57 +0000325
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000326class DocumentFragment(Node):
327 nodeType = Node.DOCUMENT_FRAGMENT_NODE
328 nodeName = "#document-fragment"
329 nodeValue = None
330 attributes = None
331 parentNode = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000332 _child_node_types = (Node.ELEMENT_NODE,
333 Node.TEXT_NODE,
334 Node.CDATA_SECTION_NODE,
335 Node.ENTITY_REFERENCE_NODE,
336 Node.PROCESSING_INSTRUCTION_NODE,
337 Node.COMMENT_NODE,
338 Node.NOTATION_NODE)
339
340 def __init__(self):
341 self.childNodes = NodeList()
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000342
343
Fred Drake55c38192000-06-29 19:39:57 +0000344class Attr(Node):
Fred Drake1f549022000-09-24 05:21:58 +0000345 nodeType = Node.ATTRIBUTE_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +0000346 attributes = None
347 ownerElement = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000348 specified = False
349 _is_id = False
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000350
Martin v. Löwis787354c2003-01-25 15:28:29 +0000351 _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE)
352
353 def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None,
354 prefix=None):
Fred Drake55c38192000-06-29 19:39:57 +0000355 # skip setattr for performance
Fred Drake4ccf4a12000-11-21 22:02:22 +0000356 d = self.__dict__
Fred Drake4ccf4a12000-11-21 22:02:22 +0000357 d["nodeName"] = d["name"] = qName
358 d["namespaceURI"] = namespaceURI
359 d["prefix"] = prefix
Martin v. Löwis787354c2003-01-25 15:28:29 +0000360 d['childNodes'] = NodeList()
361
362 # Add the single child node that represents the value of the attr
363 self.childNodes.append(Text())
364
Paul Prescod73678da2000-07-01 04:58:47 +0000365 # nodeValue and value are set elsewhere
Fred Drake55c38192000-06-29 19:39:57 +0000366
Martin v. Löwis787354c2003-01-25 15:28:29 +0000367 def _get_localName(self):
Alex Martelli0ee43512006-08-21 19:53:20 +0000368 if 'localName' in self.__dict__:
Guido van Rossum3e1f85e2007-07-27 18:03:11 +0000369 return self.__dict__['localName']
Martin v. Löwis787354c2003-01-25 15:28:29 +0000370 return self.nodeName.split(":", 1)[-1]
371
372 def _get_name(self):
373 return self.name
374
375 def _get_specified(self):
376 return self.specified
377
Fred Drake1f549022000-09-24 05:21:58 +0000378 def __setattr__(self, name, value):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000379 d = self.__dict__
Fred Drake1f549022000-09-24 05:21:58 +0000380 if name in ("value", "nodeValue"):
Fred Drakef7cf40d2000-12-14 18:16:11 +0000381 d["value"] = d["nodeValue"] = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000382 d2 = self.childNodes[0].__dict__
383 d2["data"] = d2["nodeValue"] = value
384 if self.ownerElement is not None:
385 _clear_id_cache(self.ownerElement)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000386 elif name in ("name", "nodeName"):
387 d["name"] = d["nodeName"] = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000388 if self.ownerElement is not None:
389 _clear_id_cache(self.ownerElement)
Fred Drake55c38192000-06-29 19:39:57 +0000390 else:
Fred Drakef7cf40d2000-12-14 18:16:11 +0000391 d[name] = value
Fred Drake55c38192000-06-29 19:39:57 +0000392
Martin v. Löwis995359c2003-01-26 08:59:32 +0000393 def _set_prefix(self, prefix):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000394 nsuri = self.namespaceURI
Martin v. Löwis995359c2003-01-26 08:59:32 +0000395 if prefix == "xmlns":
396 if nsuri and nsuri != XMLNS_NAMESPACE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000397 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000398 "illegal use of 'xmlns' prefix for the wrong namespace")
399 d = self.__dict__
400 d['prefix'] = prefix
401 if prefix is None:
402 newName = self.localName
403 else:
Martin v. Löwis995359c2003-01-26 08:59:32 +0000404 newName = "%s:%s" % (prefix, self.localName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000405 if self.ownerElement:
406 _clear_id_cache(self.ownerElement)
407 d['nodeName'] = d['name'] = newName
408
409 def _set_value(self, value):
410 d = self.__dict__
411 d['value'] = d['nodeValue'] = value
412 if self.ownerElement:
413 _clear_id_cache(self.ownerElement)
414 self.childNodes[0].data = value
415
416 def unlink(self):
417 # This implementation does not call the base implementation
418 # since most of that is not needed, and the expense of the
419 # method call is not warranted. We duplicate the removal of
420 # children, but that's all we needed from the base class.
421 elem = self.ownerElement
422 if elem is not None:
423 del elem._attrs[self.nodeName]
424 del elem._attrsNS[(self.namespaceURI, self.localName)]
425 if self._is_id:
426 self._is_id = False
427 elem._magic_id_nodes -= 1
428 self.ownerDocument._magic_id_count -= 1
429 for child in self.childNodes:
430 child.unlink()
431 del self.childNodes[:]
432
433 def _get_isId(self):
434 if self._is_id:
435 return True
436 doc = self.ownerDocument
437 elem = self.ownerElement
438 if doc is None or elem is None:
439 return False
440
441 info = doc._get_elem_info(elem)
442 if info is None:
443 return False
444 if self.namespaceURI:
445 return info.isIdNS(self.namespaceURI, self.localName)
446 else:
447 return info.isId(self.nodeName)
448
449 def _get_schemaType(self):
450 doc = self.ownerDocument
451 elem = self.ownerElement
452 if doc is None or elem is None:
453 return _no_type
454
455 info = doc._get_elem_info(elem)
456 if info is None:
457 return _no_type
458 if self.namespaceURI:
459 return info.getAttributeTypeNS(self.namespaceURI, self.localName)
460 else:
461 return info.getAttributeType(self.nodeName)
462
463defproperty(Attr, "isId", doc="True if this attribute is an ID.")
464defproperty(Attr, "localName", doc="Namespace-local name of this attribute.")
465defproperty(Attr, "schemaType", doc="Schema type for this attribute.")
Fred Drake4ccf4a12000-11-21 22:02:22 +0000466
Fred Drakef7cf40d2000-12-14 18:16:11 +0000467
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000468class NamedNodeMap(object):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000469 """The attribute list is a transient interface to the underlying
470 dictionaries. Mutations here will change the underlying element's
Fred Drakef7cf40d2000-12-14 18:16:11 +0000471 dictionary.
472
473 Ordering is imposed artificially and does not reflect the order of
474 attributes as found in an input document.
475 """
Fred Drake4ccf4a12000-11-21 22:02:22 +0000476
Martin v. Löwis787354c2003-01-25 15:28:29 +0000477 __slots__ = ('_attrs', '_attrsNS', '_ownerElement')
478
Fred Drake2998a552001-12-06 18:27:48 +0000479 def __init__(self, attrs, attrsNS, ownerElement):
Fred Drake1f549022000-09-24 05:21:58 +0000480 self._attrs = attrs
481 self._attrsNS = attrsNS
Fred Drake2998a552001-12-06 18:27:48 +0000482 self._ownerElement = ownerElement
Fred Drakef7cf40d2000-12-14 18:16:11 +0000483
Martin v. Löwis787354c2003-01-25 15:28:29 +0000484 def _get_length(self):
485 return len(self._attrs)
Fred Drake55c38192000-06-29 19:39:57 +0000486
Fred Drake1f549022000-09-24 05:21:58 +0000487 def item(self, index):
Fred Drake55c38192000-06-29 19:39:57 +0000488 try:
Brett Cannon861fd6f2007-02-21 22:05:37 +0000489 return self[list(self._attrs.keys())[index]]
Fred Drake55c38192000-06-29 19:39:57 +0000490 except IndexError:
491 return None
Fred Drake55c38192000-06-29 19:39:57 +0000492
Fred Drake1f549022000-09-24 05:21:58 +0000493 def items(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000494 L = []
495 for node in self._attrs.values():
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000496 L.append((node.nodeName, node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000497 return L
Fred Drake1f549022000-09-24 05:21:58 +0000498
499 def itemsNS(self):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000500 L = []
501 for node in self._attrs.values():
Fred Drake49a5d032001-11-30 22:21:58 +0000502 L.append(((node.namespaceURI, node.localName), node.value))
Fred Drake4ccf4a12000-11-21 22:02:22 +0000503 return L
Fred Drake16f63292000-10-23 18:09:50 +0000504
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000505 def __contains__(self, key):
Christian Heimesc9543e42007-11-28 08:28:28 +0000506 if isinstance(key, str):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000507 return key in self._attrs
Martin v. Löwis787354c2003-01-25 15:28:29 +0000508 else:
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000509 return key in self._attrsNS
Martin v. Löwis787354c2003-01-25 15:28:29 +0000510
Fred Drake1f549022000-09-24 05:21:58 +0000511 def keys(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000512 return self._attrs.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000513
Fred Drake1f549022000-09-24 05:21:58 +0000514 def keysNS(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000515 return self._attrsNS.keys()
Fred Drake55c38192000-06-29 19:39:57 +0000516
Fred Drake1f549022000-09-24 05:21:58 +0000517 def values(self):
Paul Prescod73678da2000-07-01 04:58:47 +0000518 return self._attrs.values()
Fred Drake55c38192000-06-29 19:39:57 +0000519
Martin v. Löwis787354c2003-01-25 15:28:29 +0000520 def get(self, name, value=None):
Martin v. Löwisd5fb58f2001-01-27 08:38:34 +0000521 return self._attrs.get(name, value)
522
Martin v. Löwis787354c2003-01-25 15:28:29 +0000523 __len__ = _get_length
Fred Drake55c38192000-06-29 19:39:57 +0000524
Mark Dickinsona56c4672009-01-27 18:17:45 +0000525 def _cmp(self, other):
Fred Drake1f549022000-09-24 05:21:58 +0000526 if self._attrs is getattr(other, "_attrs", None):
Fred Drake55c38192000-06-29 19:39:57 +0000527 return 0
Fred Drake16f63292000-10-23 18:09:50 +0000528 else:
Mark Dickinsona56c4672009-01-27 18:17:45 +0000529 return (id(self) > id(other)) - (id(self) < id(other))
530
531 def __eq__(self, other):
532 return self._cmp(other) == 0
533
534 def __ge__(self, other):
535 return self._cmp(other) >= 0
536
537 def __gt__(self, other):
538 return self._cmp(other) > 0
539
540 def __le__(self, other):
541 return self._cmp(other) <= 0
542
543 def __lt__(self, other):
544 return self._cmp(other) < 0
545
546 def __ne__(self, other):
547 return self._cmp(other) != 0
Fred Drake55c38192000-06-29 19:39:57 +0000548
Fred Drake1f549022000-09-24 05:21:58 +0000549 def __getitem__(self, attname_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000550 if isinstance(attname_or_tuple, tuple):
Paul Prescod73678da2000-07-01 04:58:47 +0000551 return self._attrsNS[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000552 else:
Paul Prescod73678da2000-07-01 04:58:47 +0000553 return self._attrs[attname_or_tuple]
Fred Drake55c38192000-06-29 19:39:57 +0000554
Paul Prescod1e688272000-07-01 19:21:47 +0000555 # same as set
Fred Drake1f549022000-09-24 05:21:58 +0000556 def __setitem__(self, attname, value):
Christian Heimesc9543e42007-11-28 08:28:28 +0000557 if isinstance(value, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000558 try:
559 node = self._attrs[attname]
560 except KeyError:
561 node = Attr(attname)
562 node.ownerDocument = self._ownerElement.ownerDocument
Martin v. Löwis995359c2003-01-26 08:59:32 +0000563 self.setNamedItem(node)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000564 node.value = value
Paul Prescod1e688272000-07-01 19:21:47 +0000565 else:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000566 if not isinstance(value, Attr):
Collin Winter70e79802007-08-24 18:57:22 +0000567 raise TypeError("value must be a string or Attr object")
Fred Drake1f549022000-09-24 05:21:58 +0000568 node = value
Martin v. Löwis787354c2003-01-25 15:28:29 +0000569 self.setNamedItem(node)
570
571 def getNamedItem(self, name):
572 try:
573 return self._attrs[name]
574 except KeyError:
575 return None
576
577 def getNamedItemNS(self, namespaceURI, localName):
578 try:
579 return self._attrsNS[(namespaceURI, localName)]
580 except KeyError:
581 return None
582
583 def removeNamedItem(self, name):
584 n = self.getNamedItem(name)
585 if n is not None:
586 _clear_id_cache(self._ownerElement)
587 del self._attrs[n.nodeName]
588 del self._attrsNS[(n.namespaceURI, n.localName)]
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000589 if 'ownerElement' in n.__dict__:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000590 n.__dict__['ownerElement'] = None
591 return n
592 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000593 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000594
595 def removeNamedItemNS(self, namespaceURI, localName):
596 n = self.getNamedItemNS(namespaceURI, localName)
597 if n is not None:
598 _clear_id_cache(self._ownerElement)
599 del self._attrsNS[(n.namespaceURI, n.localName)]
600 del self._attrs[n.nodeName]
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000601 if 'ownerElement' in n.__dict__:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000602 n.__dict__['ownerElement'] = None
603 return n
604 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000605 raise xml.dom.NotFoundErr()
Fred Drakef7cf40d2000-12-14 18:16:11 +0000606
607 def setNamedItem(self, node):
Andrew M. Kuchlingbc8f72c2001-02-21 01:30:26 +0000608 if not isinstance(node, Attr):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000609 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000610 "%s cannot be child of %s" % (repr(node), repr(self)))
Fred Drakef7cf40d2000-12-14 18:16:11 +0000611 old = self._attrs.get(node.name)
Paul Prescod1e688272000-07-01 19:21:47 +0000612 if old:
613 old.unlink()
Fred Drake1f549022000-09-24 05:21:58 +0000614 self._attrs[node.name] = node
615 self._attrsNS[(node.namespaceURI, node.localName)] = node
Fred Drake2998a552001-12-06 18:27:48 +0000616 node.ownerElement = self._ownerElement
Martin v. Löwis787354c2003-01-25 15:28:29 +0000617 _clear_id_cache(node.ownerElement)
Fred Drakef7cf40d2000-12-14 18:16:11 +0000618 return old
619
620 def setNamedItemNS(self, node):
621 return self.setNamedItem(node)
Paul Prescod73678da2000-07-01 04:58:47 +0000622
Fred Drake1f549022000-09-24 05:21:58 +0000623 def __delitem__(self, attname_or_tuple):
624 node = self[attname_or_tuple]
Martin v. Löwis787354c2003-01-25 15:28:29 +0000625 _clear_id_cache(node.ownerElement)
Paul Prescod73678da2000-07-01 04:58:47 +0000626 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000627
628 def __getstate__(self):
629 return self._attrs, self._attrsNS, self._ownerElement
630
631 def __setstate__(self, state):
632 self._attrs, self._attrsNS, self._ownerElement = state
633
634defproperty(NamedNodeMap, "length",
635 doc="Number of nodes in the NamedNodeMap.")
Fred Drakef7cf40d2000-12-14 18:16:11 +0000636
637AttributeList = NamedNodeMap
638
Fred Drake1f549022000-09-24 05:21:58 +0000639
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000640class TypeInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000641 __slots__ = 'namespace', 'name'
642
643 def __init__(self, namespace, name):
644 self.namespace = namespace
645 self.name = name
646
647 def __repr__(self):
648 if self.namespace:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000649 return "<TypeInfo %r (from %r)>" % (self.name, self.namespace)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000650 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000651 return "<TypeInfo %r>" % self.name
Martin v. Löwis787354c2003-01-25 15:28:29 +0000652
653 def _get_name(self):
654 return self.name
655
656 def _get_namespace(self):
657 return self.namespace
658
659_no_type = TypeInfo(None, None)
660
Martin v. Löwisa2fda0d2000-10-07 12:10:28 +0000661class Element(Node):
Fred Drake1f549022000-09-24 05:21:58 +0000662 nodeType = Node.ELEMENT_NODE
Martin v. Löwis787354c2003-01-25 15:28:29 +0000663 nodeValue = None
664 schemaType = _no_type
665
666 _magic_id_nodes = 0
667
668 _child_node_types = (Node.ELEMENT_NODE,
669 Node.PROCESSING_INSTRUCTION_NODE,
670 Node.COMMENT_NODE,
671 Node.TEXT_NODE,
672 Node.CDATA_SECTION_NODE,
673 Node.ENTITY_REFERENCE_NODE)
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000674
Fred Drake49a5d032001-11-30 22:21:58 +0000675 def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None,
Fred Drake1f549022000-09-24 05:21:58 +0000676 localName=None):
Fred Drake55c38192000-06-29 19:39:57 +0000677 self.tagName = self.nodeName = tagName
Fred Drake1f549022000-09-24 05:21:58 +0000678 self.prefix = prefix
679 self.namespaceURI = namespaceURI
Martin v. Löwis787354c2003-01-25 15:28:29 +0000680 self.childNodes = NodeList()
Fred Drake55c38192000-06-29 19:39:57 +0000681
Fred Drake4ccf4a12000-11-21 22:02:22 +0000682 self._attrs = {} # attributes are double-indexed:
683 self._attrsNS = {} # tagName -> Attribute
684 # URI,localName -> Attribute
685 # in the future: consider lazy generation
686 # of attribute objects this is too tricky
687 # for now because of headaches with
688 # namespaces.
689
Martin v. Löwis787354c2003-01-25 15:28:29 +0000690 def _get_localName(self):
Alex Martelli0ee43512006-08-21 19:53:20 +0000691 if 'localName' in self.__dict__:
Guido van Rossum3e1f85e2007-07-27 18:03:11 +0000692 return self.__dict__['localName']
Martin v. Löwis787354c2003-01-25 15:28:29 +0000693 return self.tagName.split(":", 1)[-1]
694
695 def _get_tagName(self):
696 return self.tagName
Fred Drake4ccf4a12000-11-21 22:02:22 +0000697
698 def unlink(self):
Brett Cannon861fd6f2007-02-21 22:05:37 +0000699 for attr in list(self._attrs.values()):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000700 attr.unlink()
701 self._attrs = None
702 self._attrsNS = None
703 Node.unlink(self)
Fred Drake55c38192000-06-29 19:39:57 +0000704
Fred Drake1f549022000-09-24 05:21:58 +0000705 def getAttribute(self, attname):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000706 try:
707 return self._attrs[attname].value
708 except KeyError:
709 return ""
Fred Drake55c38192000-06-29 19:39:57 +0000710
Fred Drake1f549022000-09-24 05:21:58 +0000711 def getAttributeNS(self, namespaceURI, localName):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000712 try:
713 return self._attrsNS[(namespaceURI, localName)].value
714 except KeyError:
715 return ""
Fred Drake1f549022000-09-24 05:21:58 +0000716
717 def setAttribute(self, attname, value):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000718 attr = self.getAttributeNode(attname)
719 if attr is None:
720 attr = Attr(attname)
721 # for performance
722 d = attr.__dict__
723 d["value"] = d["nodeValue"] = value
724 d["ownerDocument"] = self.ownerDocument
725 self.setAttributeNode(attr)
726 elif value != attr.value:
727 d = attr.__dict__
728 d["value"] = d["nodeValue"] = value
729 if attr.isId:
730 _clear_id_cache(self)
Fred Drake55c38192000-06-29 19:39:57 +0000731
Fred Drake1f549022000-09-24 05:21:58 +0000732 def setAttributeNS(self, namespaceURI, qualifiedName, value):
733 prefix, localname = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +0000734 attr = self.getAttributeNodeNS(namespaceURI, localname)
735 if attr is None:
736 # for performance
737 attr = Attr(qualifiedName, namespaceURI, localname, prefix)
738 d = attr.__dict__
739 d["prefix"] = prefix
740 d["nodeName"] = qualifiedName
741 d["value"] = d["nodeValue"] = value
742 d["ownerDocument"] = self.ownerDocument
743 self.setAttributeNode(attr)
744 else:
745 d = attr.__dict__
746 if value != attr.value:
747 d["value"] = d["nodeValue"] = value
748 if attr.isId:
749 _clear_id_cache(self)
750 if attr.prefix != prefix:
751 d["prefix"] = prefix
752 d["nodeName"] = qualifiedName
Fred Drake55c38192000-06-29 19:39:57 +0000753
Fred Drake1f549022000-09-24 05:21:58 +0000754 def getAttributeNode(self, attrname):
755 return self._attrs.get(attrname)
Paul Prescod73678da2000-07-01 04:58:47 +0000756
Fred Drake1f549022000-09-24 05:21:58 +0000757 def getAttributeNodeNS(self, namespaceURI, localName):
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000758 return self._attrsNS.get((namespaceURI, localName))
Paul Prescod73678da2000-07-01 04:58:47 +0000759
Fred Drake1f549022000-09-24 05:21:58 +0000760 def setAttributeNode(self, attr):
Fred Drake4ccf4a12000-11-21 22:02:22 +0000761 if attr.ownerElement not in (None, self):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000762 raise xml.dom.InuseAttributeErr("attribute node already owned")
Martin v. Löwis787354c2003-01-25 15:28:29 +0000763 old1 = self._attrs.get(attr.name, None)
764 if old1 is not None:
765 self.removeAttributeNode(old1)
766 old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None)
767 if old2 is not None and old2 is not old1:
768 self.removeAttributeNode(old2)
769 _set_attribute_node(self, attr)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000770
Martin v. Löwis787354c2003-01-25 15:28:29 +0000771 if old1 is not attr:
Fred Drake4ccf4a12000-11-21 22:02:22 +0000772 # It might have already been part of this node, in which case
773 # it doesn't represent a change, and should not be returned.
Martin v. Löwis787354c2003-01-25 15:28:29 +0000774 return old1
775 if old2 is not attr:
776 return old2
Fred Drake55c38192000-06-29 19:39:57 +0000777
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000778 setAttributeNodeNS = setAttributeNode
779
Fred Drake1f549022000-09-24 05:21:58 +0000780 def removeAttribute(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000781 try:
782 attr = self._attrs[name]
783 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000784 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000785 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000786
Fred Drake1f549022000-09-24 05:21:58 +0000787 def removeAttributeNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000788 try:
789 attr = self._attrsNS[(namespaceURI, localName)]
790 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000791 raise xml.dom.NotFoundErr()
Fred Drake1f549022000-09-24 05:21:58 +0000792 self.removeAttributeNode(attr)
Fred Drake55c38192000-06-29 19:39:57 +0000793
Fred Drake1f549022000-09-24 05:21:58 +0000794 def removeAttributeNode(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000795 if node is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000796 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000797 try:
798 self._attrs[node.name]
799 except KeyError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000800 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000801 _clear_id_cache(self)
Paul Prescod73678da2000-07-01 04:58:47 +0000802 node.unlink()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000803 # Restore this since the node is still useful and otherwise
804 # unlinked
805 node.ownerDocument = self.ownerDocument
Fred Drake16f63292000-10-23 18:09:50 +0000806
Martin v. Löwis126f2f62001-03-13 10:50:13 +0000807 removeAttributeNodeNS = removeAttributeNode
808
Martin v. Löwis156c3372000-12-28 18:40:56 +0000809 def hasAttribute(self, name):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000810 return name in self._attrs
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000811
Martin v. Löwis156c3372000-12-28 18:40:56 +0000812 def hasAttributeNS(self, namespaceURI, localName):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000813 return (namespaceURI, localName) in self._attrsNS
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000814
Fred Drake1f549022000-09-24 05:21:58 +0000815 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000816 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000817
Fred Drake1f549022000-09-24 05:21:58 +0000818 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000819 return _get_elements_by_tagName_ns_helper(
820 self, namespaceURI, localName, NodeList())
Fred Drake55c38192000-06-29 19:39:57 +0000821
Fred Drake1f549022000-09-24 05:21:58 +0000822 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000823 return "<DOM Element: %s at %#x>" % (self.tagName, id(self))
Fred Drake55c38192000-06-29 19:39:57 +0000824
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000825 def writexml(self, writer, indent="", addindent="", newl=""):
826 # indent = current indentation
827 # addindent = indentation to add to higher levels
828 # newl = newline string
829 writer.write(indent+"<" + self.tagName)
Fred Drake16f63292000-10-23 18:09:50 +0000830
Fred Drake4ccf4a12000-11-21 22:02:22 +0000831 attrs = self._get_attributes()
Brett Cannon861fd6f2007-02-21 22:05:37 +0000832 a_names = sorted(attrs.keys())
Fred Drake55c38192000-06-29 19:39:57 +0000833
834 for a_name in a_names:
Fred Drake1f549022000-09-24 05:21:58 +0000835 writer.write(" %s=\"" % a_name)
Fred Drake4ccf4a12000-11-21 22:02:22 +0000836 _write_data(writer, attrs[a_name].value)
Fred Drake55c38192000-06-29 19:39:57 +0000837 writer.write("\"")
838 if self.childNodes:
R David Murray791744b2011-10-01 16:19:51 -0400839 writer.write(">")
Ezio Melotti8008f2a2011-11-18 17:34:26 +0200840 if (len(self.childNodes) == 1 and
841 self.childNodes[0].nodeType == Node.TEXT_NODE):
842 self.childNodes[0].writexml(writer, '', '', '')
843 else:
R David Murray791744b2011-10-01 16:19:51 -0400844 writer.write(newl)
Ezio Melotti8008f2a2011-11-18 17:34:26 +0200845 for node in self.childNodes:
846 node.writexml(writer, indent+addindent, addindent, newl)
847 writer.write(indent)
848 writer.write("</%s>%s" % (self.tagName, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000849 else:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000850 writer.write("/>%s"%(newl))
Fred Drake55c38192000-06-29 19:39:57 +0000851
Fred Drake1f549022000-09-24 05:21:58 +0000852 def _get_attributes(self):
Fred Drake2998a552001-12-06 18:27:48 +0000853 return NamedNodeMap(self._attrs, self._attrsNS, self)
Fred Drake55c38192000-06-29 19:39:57 +0000854
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000855 def hasAttributes(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000856 if self._attrs:
857 return True
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000858 else:
Martin v. Löwis787354c2003-01-25 15:28:29 +0000859 return False
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +0000860
Martin v. Löwis787354c2003-01-25 15:28:29 +0000861 # DOM Level 3 attributes, based on the 22 Oct 2002 draft
862
863 def setIdAttribute(self, name):
864 idAttr = self.getAttributeNode(name)
865 self.setIdAttributeNode(idAttr)
866
867 def setIdAttributeNS(self, namespaceURI, localName):
868 idAttr = self.getAttributeNodeNS(namespaceURI, localName)
869 self.setIdAttributeNode(idAttr)
870
871 def setIdAttributeNode(self, idAttr):
872 if idAttr is None or not self.isSameNode(idAttr.ownerElement):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000873 raise xml.dom.NotFoundErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000874 if _get_containing_entref(self) is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000875 raise xml.dom.NoModificationAllowedErr()
Martin v. Löwis787354c2003-01-25 15:28:29 +0000876 if not idAttr._is_id:
877 idAttr.__dict__['_is_id'] = True
878 self._magic_id_nodes += 1
879 self.ownerDocument._magic_id_count += 1
880 _clear_id_cache(self)
881
882defproperty(Element, "attributes",
883 doc="NamedNodeMap of attributes on the element.")
884defproperty(Element, "localName",
885 doc="Namespace-local name of this element.")
886
887
888def _set_attribute_node(element, attr):
889 _clear_id_cache(element)
890 element._attrs[attr.name] = attr
891 element._attrsNS[(attr.namespaceURI, attr.localName)] = attr
892
893 # This creates a circular reference, but Element.unlink()
894 # breaks the cycle since the references to the attribute
895 # dictionaries are tossed.
896 attr.__dict__['ownerElement'] = element
897
898
899class Childless:
900 """Mixin that makes childless-ness easy to implement and avoids
901 the complexity of the Node methods that deal with children.
902 """
903
Fred Drake4ccf4a12000-11-21 22:02:22 +0000904 attributes = None
Martin v. Löwis787354c2003-01-25 15:28:29 +0000905 childNodes = EmptyNodeList()
906 firstChild = None
907 lastChild = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000908
Martin v. Löwis787354c2003-01-25 15:28:29 +0000909 def _get_firstChild(self):
910 return None
Fred Drake55c38192000-06-29 19:39:57 +0000911
Martin v. Löwis787354c2003-01-25 15:28:29 +0000912 def _get_lastChild(self):
913 return None
Fred Drake1f549022000-09-24 05:21:58 +0000914
Martin v. Löwis787354c2003-01-25 15:28:29 +0000915 def appendChild(self, node):
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 cannot have children")
918
919 def hasChildNodes(self):
920 return False
921
922 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000923 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000924 self.nodeName + " nodes do not have children")
925
926 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000927 raise xml.dom.NotFoundErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000928 self.nodeName + " nodes do not have children")
929
Andrew M. Kuchling688b9e32010-07-25 23:38:47 +0000930 def normalize(self):
931 # For childless nodes, normalize() has nothing to do.
932 pass
933
Martin v. Löwis787354c2003-01-25 15:28:29 +0000934 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000935 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +0000936 self.nodeName + " nodes do not have children")
937
938
939class ProcessingInstruction(Childless, Node):
Fred Drake1f549022000-09-24 05:21:58 +0000940 nodeType = Node.PROCESSING_INSTRUCTION_NODE
Martin v. Löwis52ce0d02001-01-27 08:47:37 +0000941
Fred Drake1f549022000-09-24 05:21:58 +0000942 def __init__(self, target, data):
Fred Drake55c38192000-06-29 19:39:57 +0000943 self.target = self.nodeName = target
944 self.data = self.nodeValue = data
Fred Drake55c38192000-06-29 19:39:57 +0000945
Martin v. Löwis787354c2003-01-25 15:28:29 +0000946 def _get_data(self):
947 return self.data
948 def _set_data(self, value):
949 d = self.__dict__
950 d['data'] = d['nodeValue'] = value
951
952 def _get_target(self):
953 return self.target
954 def _set_target(self, value):
955 d = self.__dict__
956 d['target'] = d['nodeName'] = value
957
958 def __setattr__(self, name, value):
959 if name == "data" or name == "nodeValue":
960 self.__dict__['data'] = self.__dict__['nodeValue'] = value
961 elif name == "target" or name == "nodeName":
962 self.__dict__['target'] = self.__dict__['nodeName'] = value
963 else:
964 self.__dict__[name] = value
965
Martin v. Löwis46fa39a2001-02-06 00:14:08 +0000966 def writexml(self, writer, indent="", addindent="", newl=""):
967 writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +0000968
Martin v. Löwis787354c2003-01-25 15:28:29 +0000969
970class CharacterData(Childless, Node):
971 def _get_length(self):
972 return len(self.data)
973 __len__ = _get_length
974
975 def _get_data(self):
976 return self.__dict__['data']
977 def _set_data(self, data):
978 d = self.__dict__
979 d['data'] = d['nodeValue'] = data
980
981 _get_nodeValue = _get_data
982 _set_nodeValue = _set_data
983
984 def __setattr__(self, name, value):
985 if name == "data" or name == "nodeValue":
986 self.__dict__['data'] = self.__dict__['nodeValue'] = value
987 else:
988 self.__dict__[name] = value
Fred Drake87432f42001-04-04 14:09:46 +0000989
Fred Drake55c38192000-06-29 19:39:57 +0000990 def __repr__(self):
Martin v. Löwis787354c2003-01-25 15:28:29 +0000991 data = self.data
992 if len(data) > 10:
Fred Drake1f549022000-09-24 05:21:58 +0000993 dotdotdot = "..."
Fred Drake55c38192000-06-29 19:39:57 +0000994 else:
Fred Drake1f549022000-09-24 05:21:58 +0000995 dotdotdot = ""
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000996 return '<DOM %s node "%r%s">' % (
Martin v. Löwis787354c2003-01-25 15:28:29 +0000997 self.__class__.__name__, data[0:10], dotdotdot)
Fred Drake87432f42001-04-04 14:09:46 +0000998
999 def substringData(self, offset, count):
1000 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001001 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001002 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001003 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001004 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001005 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001006 return self.data[offset:offset+count]
1007
1008 def appendData(self, arg):
1009 self.data = self.data + arg
Fred Drake87432f42001-04-04 14:09:46 +00001010
1011 def insertData(self, offset, arg):
1012 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001013 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001014 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001015 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001016 if arg:
1017 self.data = "%s%s%s" % (
1018 self.data[:offset], arg, self.data[offset:])
Fred Drake87432f42001-04-04 14:09:46 +00001019
1020 def deleteData(self, offset, count):
1021 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001022 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001023 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001024 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001025 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001026 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001027 if count:
1028 self.data = self.data[:offset] + self.data[offset+count:]
Fred Drake87432f42001-04-04 14:09:46 +00001029
1030 def replaceData(self, offset, count, arg):
1031 if offset < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001032 raise xml.dom.IndexSizeErr("offset cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001033 if offset >= len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001034 raise xml.dom.IndexSizeErr("offset cannot be beyond end of data")
Fred Drake87432f42001-04-04 14:09:46 +00001035 if count < 0:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001036 raise xml.dom.IndexSizeErr("count cannot be negative")
Fred Drake87432f42001-04-04 14:09:46 +00001037 if count:
1038 self.data = "%s%s%s" % (
1039 self.data[:offset], arg, self.data[offset+count:])
Martin v. Löwis787354c2003-01-25 15:28:29 +00001040
1041defproperty(CharacterData, "length", doc="Length of the string data.")
1042
Fred Drake87432f42001-04-04 14:09:46 +00001043
1044class Text(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001045 # Make sure we don't add an instance __dict__ if we don't already
1046 # have one, at least when that's possible:
Martin v. Löwis995359c2003-01-26 08:59:32 +00001047 # XXX this does not work, CharacterData is an old-style class
1048 # __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001049
Fred Drake87432f42001-04-04 14:09:46 +00001050 nodeType = Node.TEXT_NODE
1051 nodeName = "#text"
1052 attributes = None
Fred Drake55c38192000-06-29 19:39:57 +00001053
Fred Drakef7cf40d2000-12-14 18:16:11 +00001054 def splitText(self, offset):
1055 if offset < 0 or offset > len(self.data):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001056 raise xml.dom.IndexSizeErr("illegal offset value")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001057 newText = self.__class__()
1058 newText.data = self.data[offset:]
1059 newText.ownerDocument = self.ownerDocument
Fred Drakef7cf40d2000-12-14 18:16:11 +00001060 next = self.nextSibling
1061 if self.parentNode and self in self.parentNode.childNodes:
1062 if next is None:
1063 self.parentNode.appendChild(newText)
1064 else:
1065 self.parentNode.insertBefore(newText, next)
1066 self.data = self.data[:offset]
1067 return newText
1068
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001069 def writexml(self, writer, indent="", addindent="", newl=""):
Ezio Melotti8008f2a2011-11-18 17:34:26 +02001070 _write_data(writer, "%s%s%s" % (indent, self.data, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001071
Martin v. Löwis787354c2003-01-25 15:28:29 +00001072 # DOM Level 3 (WD 9 April 2002)
1073
1074 def _get_wholeText(self):
1075 L = [self.data]
1076 n = self.previousSibling
1077 while n is not None:
1078 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1079 L.insert(0, n.data)
1080 n = n.previousSibling
1081 else:
1082 break
1083 n = self.nextSibling
1084 while n is not None:
1085 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1086 L.append(n.data)
1087 n = n.nextSibling
1088 else:
1089 break
1090 return ''.join(L)
1091
1092 def replaceWholeText(self, content):
1093 # XXX This needs to be seriously changed if minidom ever
1094 # supports EntityReference nodes.
1095 parent = self.parentNode
1096 n = self.previousSibling
1097 while n is not None:
1098 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1099 next = n.previousSibling
1100 parent.removeChild(n)
1101 n = next
1102 else:
1103 break
1104 n = self.nextSibling
1105 if not content:
1106 parent.removeChild(self)
1107 while n is not None:
1108 if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
1109 next = n.nextSibling
1110 parent.removeChild(n)
1111 n = next
1112 else:
1113 break
1114 if content:
1115 d = self.__dict__
1116 d['data'] = content
1117 d['nodeValue'] = content
1118 return self
1119 else:
1120 return None
1121
1122 def _get_isWhitespaceInElementContent(self):
1123 if self.data.strip():
1124 return False
1125 elem = _get_containing_element(self)
1126 if elem is None:
1127 return False
1128 info = self.ownerDocument._get_elem_info(elem)
1129 if info is None:
1130 return False
1131 else:
1132 return info.isElementContent()
1133
1134defproperty(Text, "isWhitespaceInElementContent",
1135 doc="True iff this text node contains only whitespace"
1136 " and is in element content.")
1137defproperty(Text, "wholeText",
1138 doc="The text of all logically-adjacent text nodes.")
1139
1140
1141def _get_containing_element(node):
1142 c = node.parentNode
1143 while c is not None:
1144 if c.nodeType == Node.ELEMENT_NODE:
1145 return c
1146 c = c.parentNode
1147 return None
1148
1149def _get_containing_entref(node):
1150 c = node.parentNode
1151 while c is not None:
1152 if c.nodeType == Node.ENTITY_REFERENCE_NODE:
1153 return c
1154 c = c.parentNode
1155 return None
1156
1157
Alex Martelli0ee43512006-08-21 19:53:20 +00001158class Comment(CharacterData):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001159 nodeType = Node.COMMENT_NODE
1160 nodeName = "#comment"
1161
1162 def __init__(self, data):
1163 self.data = self.nodeValue = data
1164
1165 def writexml(self, writer, indent="", addindent="", newl=""):
Benjamin Peterson2b7411d2008-05-26 17:36:47 +00001166 if "--" in self.data:
1167 raise ValueError("'--' is not allowed in a comment node")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001168 writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1169
Fred Drake87432f42001-04-04 14:09:46 +00001170
1171class CDATASection(Text):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001172 # Make sure we don't add an instance __dict__ if we don't already
1173 # have one, at least when that's possible:
Martin v. Löwis995359c2003-01-26 08:59:32 +00001174 # XXX this does not work, Text is an old-style class
1175 # __slots__ = ()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001176
Fred Drake87432f42001-04-04 14:09:46 +00001177 nodeType = Node.CDATA_SECTION_NODE
1178 nodeName = "#cdata-section"
1179
1180 def writexml(self, writer, indent="", addindent="", newl=""):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001181 if self.data.find("]]>") >= 0:
1182 raise ValueError("']]>' not allowed in a CDATA section")
Guido van Rossum5b5e0b92001-09-19 13:28:25 +00001183 writer.write("<![CDATA[%s]]>" % self.data)
Fred Drake87432f42001-04-04 14:09:46 +00001184
1185
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001186class ReadOnlySequentialNamedNodeMap(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001187 __slots__ = '_seq',
1188
1189 def __init__(self, seq=()):
1190 # seq should be a list or tuple
1191 self._seq = seq
1192
1193 def __len__(self):
1194 return len(self._seq)
1195
1196 def _get_length(self):
1197 return len(self._seq)
1198
1199 def getNamedItem(self, name):
1200 for n in self._seq:
1201 if n.nodeName == name:
1202 return n
1203
1204 def getNamedItemNS(self, namespaceURI, localName):
1205 for n in self._seq:
1206 if n.namespaceURI == namespaceURI and n.localName == localName:
1207 return n
1208
1209 def __getitem__(self, name_or_tuple):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001210 if isinstance(name_or_tuple, tuple):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001211 node = self.getNamedItemNS(*name_or_tuple)
1212 else:
1213 node = self.getNamedItem(name_or_tuple)
1214 if node is None:
Collin Winter70e79802007-08-24 18:57:22 +00001215 raise KeyError(name_or_tuple)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001216 return node
1217
1218 def item(self, index):
1219 if index < 0:
1220 return None
1221 try:
1222 return self._seq[index]
1223 except IndexError:
1224 return None
1225
1226 def removeNamedItem(self, name):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001227 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001228 "NamedNodeMap instance is read-only")
1229
1230 def removeNamedItemNS(self, namespaceURI, localName):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001231 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001232 "NamedNodeMap instance is read-only")
1233
1234 def setNamedItem(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001235 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001236 "NamedNodeMap instance is read-only")
1237
1238 def setNamedItemNS(self, node):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001239 raise xml.dom.NoModificationAllowedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001240 "NamedNodeMap instance is read-only")
1241
1242 def __getstate__(self):
1243 return [self._seq]
1244
1245 def __setstate__(self, state):
1246 self._seq = state[0]
1247
1248defproperty(ReadOnlySequentialNamedNodeMap, "length",
1249 doc="Number of entries in the NamedNodeMap.")
Paul Prescod73678da2000-07-01 04:58:47 +00001250
Fred Drakef7cf40d2000-12-14 18:16:11 +00001251
Martin v. Löwis787354c2003-01-25 15:28:29 +00001252class Identified:
1253 """Mix-in class that supports the publicId and systemId attributes."""
1254
Martin v. Löwis995359c2003-01-26 08:59:32 +00001255 # XXX this does not work, this is an old-style class
1256 # __slots__ = 'publicId', 'systemId'
Martin v. Löwis787354c2003-01-25 15:28:29 +00001257
1258 def _identified_mixin_init(self, publicId, systemId):
1259 self.publicId = publicId
1260 self.systemId = systemId
1261
1262 def _get_publicId(self):
1263 return self.publicId
1264
1265 def _get_systemId(self):
1266 return self.systemId
1267
1268class DocumentType(Identified, Childless, Node):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001269 nodeType = Node.DOCUMENT_TYPE_NODE
1270 nodeValue = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001271 name = None
1272 publicId = None
1273 systemId = None
Fred Drakedc806702001-04-05 14:41:30 +00001274 internalSubset = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001275
1276 def __init__(self, qualifiedName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001277 self.entities = ReadOnlySequentialNamedNodeMap()
1278 self.notations = ReadOnlySequentialNamedNodeMap()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001279 if qualifiedName:
1280 prefix, localname = _nssplit(qualifiedName)
1281 self.name = localname
Martin v. Löwis787354c2003-01-25 15:28:29 +00001282 self.nodeName = self.name
1283
1284 def _get_internalSubset(self):
1285 return self.internalSubset
1286
1287 def cloneNode(self, deep):
1288 if self.ownerDocument is None:
1289 # it's ok
1290 clone = DocumentType(None)
1291 clone.name = self.name
1292 clone.nodeName = self.name
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001293 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001294 if deep:
1295 clone.entities._seq = []
1296 clone.notations._seq = []
1297 for n in self.notations._seq:
1298 notation = Notation(n.nodeName, n.publicId, n.systemId)
1299 clone.notations._seq.append(notation)
1300 n._call_user_data_handler(operation, n, notation)
1301 for e in self.entities._seq:
1302 entity = Entity(e.nodeName, e.publicId, e.systemId,
1303 e.notationName)
1304 entity.actualEncoding = e.actualEncoding
1305 entity.encoding = e.encoding
1306 entity.version = e.version
1307 clone.entities._seq.append(entity)
1308 e._call_user_data_handler(operation, n, entity)
1309 self._call_user_data_handler(operation, self, clone)
1310 return clone
1311 else:
1312 return None
1313
1314 def writexml(self, writer, indent="", addindent="", newl=""):
1315 writer.write("<!DOCTYPE ")
1316 writer.write(self.name)
1317 if self.publicId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001318 writer.write("%s PUBLIC '%s'%s '%s'"
1319 % (newl, self.publicId, newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001320 elif self.systemId:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001321 writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001322 if self.internalSubset is not None:
1323 writer.write(" [")
1324 writer.write(self.internalSubset)
1325 writer.write("]")
Georg Brandl175a7dc2005-08-25 22:02:43 +00001326 writer.write(">"+newl)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001327
1328class Entity(Identified, Node):
1329 attributes = None
1330 nodeType = Node.ENTITY_NODE
1331 nodeValue = None
1332
1333 actualEncoding = None
1334 encoding = None
1335 version = None
1336
1337 def __init__(self, name, publicId, systemId, notation):
1338 self.nodeName = name
1339 self.notationName = notation
1340 self.childNodes = NodeList()
1341 self._identified_mixin_init(publicId, systemId)
1342
1343 def _get_actualEncoding(self):
1344 return self.actualEncoding
1345
1346 def _get_encoding(self):
1347 return self.encoding
1348
1349 def _get_version(self):
1350 return self.version
1351
1352 def appendChild(self, newChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001353 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001354 "cannot append children to an entity node")
1355
1356 def insertBefore(self, newChild, refChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001357 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001358 "cannot insert children below an entity node")
1359
1360 def removeChild(self, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001361 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001362 "cannot remove children from an entity node")
1363
1364 def replaceChild(self, newChild, oldChild):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001365 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001366 "cannot replace children of an entity node")
1367
1368class Notation(Identified, Childless, Node):
1369 nodeType = Node.NOTATION_NODE
1370 nodeValue = None
1371
1372 def __init__(self, name, publicId, systemId):
1373 self.nodeName = name
1374 self._identified_mixin_init(publicId, systemId)
Fred Drakef7cf40d2000-12-14 18:16:11 +00001375
1376
Martin v. Löwis787354c2003-01-25 15:28:29 +00001377class DOMImplementation(DOMImplementationLS):
1378 _features = [("core", "1.0"),
1379 ("core", "2.0"),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001380 ("core", None),
1381 ("xml", "1.0"),
1382 ("xml", "2.0"),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001383 ("xml", None),
1384 ("ls-load", "3.0"),
1385 ("ls-load", None),
1386 ]
1387
Fred Drakef7cf40d2000-12-14 18:16:11 +00001388 def hasFeature(self, feature, version):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001389 if version == "":
1390 version = None
1391 return (feature.lower(), version) in self._features
Fred Drakef7cf40d2000-12-14 18:16:11 +00001392
1393 def createDocument(self, namespaceURI, qualifiedName, doctype):
1394 if doctype and doctype.parentNode is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001395 raise xml.dom.WrongDocumentErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001396 "doctype object owned by another DOM tree")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001397 doc = self._create_document()
1398
1399 add_root_element = not (namespaceURI is None
1400 and qualifiedName is None
1401 and doctype is None)
1402
1403 if not qualifiedName and add_root_element:
Martin v. Löwisb417be22001-02-06 01:16:06 +00001404 # The spec is unclear what to raise here; SyntaxErr
1405 # would be the other obvious candidate. Since Xerces raises
1406 # InvalidCharacterErr, and since SyntaxErr is not listed
1407 # for createDocument, that seems to be the better choice.
1408 # XXX: need to check for illegal characters here and in
1409 # createElement.
Martin v. Löwis787354c2003-01-25 15:28:29 +00001410
1411 # DOM Level III clears this up when talking about the return value
1412 # of this function. If namespaceURI, qName and DocType are
1413 # Null the document is returned without a document element
1414 # Otherwise if doctype or namespaceURI are not None
1415 # Then we go back to the above problem
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001416 raise xml.dom.InvalidCharacterErr("Element with no name")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001417
1418 if add_root_element:
1419 prefix, localname = _nssplit(qualifiedName)
1420 if prefix == "xml" \
1421 and namespaceURI != "http://www.w3.org/XML/1998/namespace":
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001422 raise xml.dom.NamespaceErr("illegal use of 'xml' prefix")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001423 if prefix and not namespaceURI:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001424 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001425 "illegal use of prefix without namespaces")
1426 element = doc.createElementNS(namespaceURI, qualifiedName)
1427 if doctype:
1428 doc.appendChild(doctype)
1429 doc.appendChild(element)
1430
1431 if doctype:
1432 doctype.parentNode = doctype.ownerDocument = doc
1433
Fred Drakef7cf40d2000-12-14 18:16:11 +00001434 doc.doctype = doctype
1435 doc.implementation = self
1436 return doc
1437
1438 def createDocumentType(self, qualifiedName, publicId, systemId):
1439 doctype = DocumentType(qualifiedName)
1440 doctype.publicId = publicId
1441 doctype.systemId = systemId
1442 return doctype
1443
Martin v. Löwis787354c2003-01-25 15:28:29 +00001444 # DOM Level 3 (WD 9 April 2002)
1445
1446 def getInterface(self, feature):
1447 if self.hasFeature(feature, None):
1448 return self
1449 else:
1450 return None
1451
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001452 # internal
Martin v. Löwis787354c2003-01-25 15:28:29 +00001453 def _create_document(self):
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001454 return Document()
Fred Drakef7cf40d2000-12-14 18:16:11 +00001455
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001456class ElementInfo(object):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001457 """Object that represents content-model information for an element.
1458
1459 This implementation is not expected to be used in practice; DOM
1460 builders should provide implementations which do the right thing
1461 using information available to it.
1462
1463 """
1464
1465 __slots__ = 'tagName',
1466
1467 def __init__(self, name):
1468 self.tagName = name
1469
1470 def getAttributeType(self, aname):
1471 return _no_type
1472
1473 def getAttributeTypeNS(self, namespaceURI, localName):
1474 return _no_type
1475
1476 def isElementContent(self):
1477 return False
1478
1479 def isEmpty(self):
1480 """Returns true iff this element is declared to have an EMPTY
1481 content model."""
1482 return False
1483
1484 def isId(self, aname):
Ezio Melotti42da6632011-03-15 05:18:48 +02001485 """Returns true iff the named attribute is a DTD-style ID."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001486 return False
1487
1488 def isIdNS(self, namespaceURI, localName):
1489 """Returns true iff the identified attribute is a DTD-style ID."""
1490 return False
1491
1492 def __getstate__(self):
1493 return self.tagName
1494
1495 def __setstate__(self, state):
1496 self.tagName = state
1497
1498def _clear_id_cache(node):
1499 if node.nodeType == Node.DOCUMENT_NODE:
1500 node._id_cache.clear()
1501 node._id_search_stack = None
1502 elif _in_document(node):
1503 node.ownerDocument._id_cache.clear()
1504 node.ownerDocument._id_search_stack= None
1505
1506class Document(Node, DocumentLS):
1507 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE,
1508 Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE)
1509
Fred Drake1f549022000-09-24 05:21:58 +00001510 nodeType = Node.DOCUMENT_NODE
Fred Drake4ccf4a12000-11-21 22:02:22 +00001511 nodeName = "#document"
1512 nodeValue = None
1513 attributes = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001514 doctype = None
1515 parentNode = None
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001516 previousSibling = nextSibling = None
Fred Drakef7cf40d2000-12-14 18:16:11 +00001517
1518 implementation = DOMImplementation()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001519
1520 # Document attributes from Level 3 (WD 9 April 2002)
1521
1522 actualEncoding = None
1523 encoding = None
1524 standalone = None
1525 version = None
1526 strictErrorChecking = False
1527 errorHandler = None
1528 documentURI = None
1529
1530 _magic_id_count = 0
1531
1532 def __init__(self):
1533 self.childNodes = NodeList()
1534 # mapping of (namespaceURI, localName) -> ElementInfo
1535 # and tagName -> ElementInfo
1536 self._elem_info = {}
1537 self._id_cache = {}
1538 self._id_search_stack = None
1539
1540 def _get_elem_info(self, element):
1541 if element.namespaceURI:
1542 key = element.namespaceURI, element.localName
1543 else:
1544 key = element.tagName
1545 return self._elem_info.get(key)
1546
1547 def _get_actualEncoding(self):
1548 return self.actualEncoding
1549
1550 def _get_doctype(self):
1551 return self.doctype
1552
1553 def _get_documentURI(self):
1554 return self.documentURI
1555
1556 def _get_encoding(self):
1557 return self.encoding
1558
1559 def _get_errorHandler(self):
1560 return self.errorHandler
1561
1562 def _get_standalone(self):
1563 return self.standalone
1564
1565 def _get_strictErrorChecking(self):
1566 return self.strictErrorChecking
1567
1568 def _get_version(self):
1569 return self.version
Fred Drake55c38192000-06-29 19:39:57 +00001570
Fred Drake1f549022000-09-24 05:21:58 +00001571 def appendChild(self, node):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001572 if node.nodeType not in self._child_node_types:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001573 raise xml.dom.HierarchyRequestErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001574 "%s cannot be child of %s" % (repr(node), repr(self)))
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001575 if node.parentNode is not None:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001576 # This needs to be done before the next test since this
1577 # may *be* the document element, in which case it should
1578 # end up re-ordered to the end.
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001579 node.parentNode.removeChild(node)
1580
Fred Drakef7cf40d2000-12-14 18:16:11 +00001581 if node.nodeType == Node.ELEMENT_NODE \
1582 and self._get_documentElement():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001583 raise xml.dom.HierarchyRequestErr(
Guido van Rossum9e1fe1e2001-02-05 19:17:50 +00001584 "two document elements disallowed")
Fred Drake4ccf4a12000-11-21 22:02:22 +00001585 return Node.appendChild(self, node)
Paul Prescod73678da2000-07-01 04:58:47 +00001586
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001587 def removeChild(self, oldChild):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001588 try:
1589 self.childNodes.remove(oldChild)
1590 except ValueError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001591 raise xml.dom.NotFoundErr()
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001592 oldChild.nextSibling = oldChild.previousSibling = None
1593 oldChild.parentNode = None
1594 if self.documentElement is oldChild:
1595 self.documentElement = None
Martin v. Löwis52ce0d02001-01-27 08:47:37 +00001596
Andrew M. Kuchling04a45e92000-12-20 14:47:24 +00001597 return oldChild
1598
Fred Drakef7cf40d2000-12-14 18:16:11 +00001599 def _get_documentElement(self):
1600 for node in self.childNodes:
1601 if node.nodeType == Node.ELEMENT_NODE:
1602 return node
1603
1604 def unlink(self):
1605 if self.doctype is not None:
1606 self.doctype.unlink()
1607 self.doctype = None
1608 Node.unlink(self)
1609
Martin v. Löwis787354c2003-01-25 15:28:29 +00001610 def cloneNode(self, deep):
1611 if not deep:
1612 return None
1613 clone = self.implementation.createDocument(None, None, None)
1614 clone.encoding = self.encoding
1615 clone.standalone = self.standalone
1616 clone.version = self.version
1617 for n in self.childNodes:
1618 childclone = _clone_node(n, deep, clone)
1619 assert childclone.ownerDocument.isSameNode(clone)
1620 clone.childNodes.append(childclone)
1621 if childclone.nodeType == Node.DOCUMENT_NODE:
1622 assert clone.documentElement is None
1623 elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE:
1624 assert clone.doctype is None
1625 clone.doctype = childclone
1626 childclone.parentNode = clone
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001627 self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED,
Martin v. Löwis787354c2003-01-25 15:28:29 +00001628 self, clone)
1629 return clone
1630
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001631 def createDocumentFragment(self):
1632 d = DocumentFragment()
Martin v. Löwis787354c2003-01-25 15:28:29 +00001633 d.ownerDocument = self
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001634 return d
Fred Drake55c38192000-06-29 19:39:57 +00001635
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001636 def createElement(self, tagName):
1637 e = Element(tagName)
1638 e.ownerDocument = self
1639 return e
Fred Drake55c38192000-06-29 19:39:57 +00001640
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001641 def createTextNode(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001642 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001643 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001644 t = Text()
1645 t.data = data
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001646 t.ownerDocument = self
1647 return t
Fred Drake55c38192000-06-29 19:39:57 +00001648
Fred Drake87432f42001-04-04 14:09:46 +00001649 def createCDATASection(self, data):
Christian Heimesc9543e42007-11-28 08:28:28 +00001650 if not isinstance(data, str):
Collin Winter70e79802007-08-24 18:57:22 +00001651 raise TypeError("node contents must be a string")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001652 c = CDATASection()
1653 c.data = data
Fred Drake87432f42001-04-04 14:09:46 +00001654 c.ownerDocument = self
1655 return c
1656
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001657 def createComment(self, data):
1658 c = Comment(data)
1659 c.ownerDocument = self
1660 return c
Fred Drake55c38192000-06-29 19:39:57 +00001661
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001662 def createProcessingInstruction(self, target, data):
1663 p = ProcessingInstruction(target, data)
1664 p.ownerDocument = self
1665 return p
1666
1667 def createAttribute(self, qName):
1668 a = Attr(qName)
1669 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001670 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001671 return a
Fred Drake55c38192000-06-29 19:39:57 +00001672
1673 def createElementNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001674 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis787354c2003-01-25 15:28:29 +00001675 e = Element(qualifiedName, namespaceURI, prefix)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001676 e.ownerDocument = self
1677 return e
Fred Drake55c38192000-06-29 19:39:57 +00001678
1679 def createAttributeNS(self, namespaceURI, qualifiedName):
Fred Drake4ccf4a12000-11-21 22:02:22 +00001680 prefix, localName = _nssplit(qualifiedName)
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001681 a = Attr(qualifiedName, namespaceURI, localName, prefix)
1682 a.ownerDocument = self
Martin v. Löwiscb67ea12001-03-31 16:30:40 +00001683 a.value = ""
Martin v. Löwis126f2f62001-03-13 10:50:13 +00001684 return a
Fred Drake55c38192000-06-29 19:39:57 +00001685
Martin v. Löwis787354c2003-01-25 15:28:29 +00001686 # A couple of implementation-specific helpers to create node types
1687 # not supported by the W3C DOM specs:
1688
1689 def _create_entity(self, name, publicId, systemId, notationName):
1690 e = Entity(name, publicId, systemId, notationName)
1691 e.ownerDocument = self
1692 return e
1693
1694 def _create_notation(self, name, publicId, systemId):
1695 n = Notation(name, publicId, systemId)
1696 n.ownerDocument = self
1697 return n
1698
1699 def getElementById(self, id):
Guido van Rossum1b01e5c2006-08-19 02:45:06 +00001700 if id in self._id_cache:
Martin v. Löwis787354c2003-01-25 15:28:29 +00001701 return self._id_cache[id]
1702 if not (self._elem_info or self._magic_id_count):
1703 return None
1704
1705 stack = self._id_search_stack
1706 if stack is None:
1707 # we never searched before, or the cache has been cleared
1708 stack = [self.documentElement]
1709 self._id_search_stack = stack
1710 elif not stack:
1711 # Previous search was completed and cache is still valid;
1712 # no matching node.
1713 return None
1714
1715 result = None
1716 while stack:
1717 node = stack.pop()
1718 # add child elements to stack for continued searching
1719 stack.extend([child for child in node.childNodes
1720 if child.nodeType in _nodeTypes_with_children])
1721 # check this node
1722 info = self._get_elem_info(node)
1723 if info:
1724 # We have to process all ID attributes before
1725 # returning in order to get all the attributes set to
1726 # be IDs using Element.setIdAttribute*().
1727 for attr in node.attributes.values():
1728 if attr.namespaceURI:
1729 if info.isIdNS(attr.namespaceURI, attr.localName):
1730 self._id_cache[attr.value] = node
1731 if attr.value == id:
1732 result = node
1733 elif not node._magic_id_nodes:
1734 break
1735 elif info.isId(attr.name):
1736 self._id_cache[attr.value] = node
1737 if attr.value == id:
1738 result = node
1739 elif not node._magic_id_nodes:
1740 break
1741 elif attr._is_id:
1742 self._id_cache[attr.value] = node
1743 if attr.value == id:
1744 result = node
1745 elif node._magic_id_nodes == 1:
1746 break
1747 elif node._magic_id_nodes:
1748 for attr in node.attributes.values():
1749 if attr._is_id:
1750 self._id_cache[attr.value] = node
1751 if attr.value == id:
1752 result = node
1753 if result is not None:
1754 break
1755 return result
1756
Fred Drake1f549022000-09-24 05:21:58 +00001757 def getElementsByTagName(self, name):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001758 return _get_elements_by_tagName_helper(self, name, NodeList())
Fred Drakefbe7b4f2001-07-04 06:25:53 +00001759
1760 def getElementsByTagNameNS(self, namespaceURI, localName):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001761 return _get_elements_by_tagName_ns_helper(
1762 self, namespaceURI, localName, NodeList())
1763
1764 def isSupported(self, feature, version):
1765 return self.implementation.hasFeature(feature, version)
1766
1767 def importNode(self, node, deep):
1768 if node.nodeType == Node.DOCUMENT_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001769 raise xml.dom.NotSupportedErr("cannot import document nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001770 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001771 raise xml.dom.NotSupportedErr("cannot import document type nodes")
Martin v. Löwis787354c2003-01-25 15:28:29 +00001772 return _clone_node(node, deep, self)
Fred Drake55c38192000-06-29 19:39:57 +00001773
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001774 def writexml(self, writer, indent="", addindent="", newl="",
1775 encoding = None):
1776 if encoding is None:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001777 writer.write('<?xml version="1.0" ?>'+newl)
Martin v. Löwis7d650ca2002-06-30 15:05:00 +00001778 else:
Georg Brandl175a7dc2005-08-25 22:02:43 +00001779 writer.write('<?xml version="1.0" encoding="%s"?>%s' % (encoding, newl))
Fred Drake55c38192000-06-29 19:39:57 +00001780 for node in self.childNodes:
Martin v. Löwis46fa39a2001-02-06 00:14:08 +00001781 node.writexml(writer, indent, addindent, newl)
Fred Drake55c38192000-06-29 19:39:57 +00001782
Martin v. Löwis787354c2003-01-25 15:28:29 +00001783 # DOM Level 3 (WD 9 April 2002)
1784
1785 def renameNode(self, n, namespaceURI, name):
1786 if n.ownerDocument is not self:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001787 raise xml.dom.WrongDocumentErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001788 "cannot rename nodes from other documents;\n"
1789 "expected %s,\nfound %s" % (self, n.ownerDocument))
1790 if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001791 raise xml.dom.NotSupportedErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001792 "renameNode() only applies to element and attribute nodes")
1793 if namespaceURI != EMPTY_NAMESPACE:
1794 if ':' in name:
1795 prefix, localName = name.split(':', 1)
1796 if ( prefix == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001797 and namespaceURI != xml.dom.XMLNS_NAMESPACE):
1798 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001799 "illegal use of 'xmlns' prefix")
1800 else:
1801 if ( name == "xmlns"
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001802 and namespaceURI != xml.dom.XMLNS_NAMESPACE
Martin v. Löwis787354c2003-01-25 15:28:29 +00001803 and n.nodeType == Node.ATTRIBUTE_NODE):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001804 raise xml.dom.NamespaceErr(
Martin v. Löwis787354c2003-01-25 15:28:29 +00001805 "illegal use of the 'xmlns' attribute")
1806 prefix = None
1807 localName = name
1808 else:
1809 prefix = None
1810 localName = None
1811 if n.nodeType == Node.ATTRIBUTE_NODE:
1812 element = n.ownerElement
1813 if element is not None:
1814 is_id = n._is_id
1815 element.removeAttributeNode(n)
1816 else:
1817 element = None
1818 # avoid __setattr__
1819 d = n.__dict__
1820 d['prefix'] = prefix
1821 d['localName'] = localName
1822 d['namespaceURI'] = namespaceURI
1823 d['nodeName'] = name
1824 if n.nodeType == Node.ELEMENT_NODE:
1825 d['tagName'] = name
1826 else:
1827 # attribute node
1828 d['name'] = name
1829 if element is not None:
1830 element.setAttributeNode(n)
1831 if is_id:
1832 element.setIdAttributeNode(n)
1833 # It's not clear from a semantic perspective whether we should
1834 # call the user data handlers for the NODE_RENAMED event since
1835 # we're re-using the existing node. The draft spec has been
1836 # interpreted as meaning "no, don't call the handler unless a
1837 # new node is created."
1838 return n
1839
1840defproperty(Document, "documentElement",
1841 doc="Top-level element of this document.")
1842
1843
1844def _clone_node(node, deep, newOwnerDocument):
1845 """
1846 Clone a node and give it the new owner document.
1847 Called by Node.cloneNode and Document.importNode
1848 """
1849 if node.ownerDocument.isSameNode(newOwnerDocument):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001850 operation = xml.dom.UserDataHandler.NODE_CLONED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001851 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001852 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001853 if node.nodeType == Node.ELEMENT_NODE:
1854 clone = newOwnerDocument.createElementNS(node.namespaceURI,
1855 node.nodeName)
1856 for attr in node.attributes.values():
1857 clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)
1858 a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)
1859 a.specified = attr.specified
1860
1861 if deep:
1862 for child in node.childNodes:
1863 c = _clone_node(child, deep, newOwnerDocument)
1864 clone.appendChild(c)
1865
1866 elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE:
1867 clone = newOwnerDocument.createDocumentFragment()
1868 if deep:
1869 for child in node.childNodes:
1870 c = _clone_node(child, deep, newOwnerDocument)
1871 clone.appendChild(c)
1872
1873 elif node.nodeType == Node.TEXT_NODE:
1874 clone = newOwnerDocument.createTextNode(node.data)
1875 elif node.nodeType == Node.CDATA_SECTION_NODE:
1876 clone = newOwnerDocument.createCDATASection(node.data)
1877 elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
1878 clone = newOwnerDocument.createProcessingInstruction(node.target,
1879 node.data)
1880 elif node.nodeType == Node.COMMENT_NODE:
1881 clone = newOwnerDocument.createComment(node.data)
1882 elif node.nodeType == Node.ATTRIBUTE_NODE:
1883 clone = newOwnerDocument.createAttributeNS(node.namespaceURI,
1884 node.nodeName)
1885 clone.specified = True
1886 clone.value = node.value
1887 elif node.nodeType == Node.DOCUMENT_TYPE_NODE:
1888 assert node.ownerDocument is not newOwnerDocument
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001889 operation = xml.dom.UserDataHandler.NODE_IMPORTED
Martin v. Löwis787354c2003-01-25 15:28:29 +00001890 clone = newOwnerDocument.implementation.createDocumentType(
1891 node.name, node.publicId, node.systemId)
1892 clone.ownerDocument = newOwnerDocument
1893 if deep:
1894 clone.entities._seq = []
1895 clone.notations._seq = []
1896 for n in node.notations._seq:
1897 notation = Notation(n.nodeName, n.publicId, n.systemId)
1898 notation.ownerDocument = newOwnerDocument
1899 clone.notations._seq.append(notation)
1900 if hasattr(n, '_call_user_data_handler'):
1901 n._call_user_data_handler(operation, n, notation)
1902 for e in node.entities._seq:
1903 entity = Entity(e.nodeName, e.publicId, e.systemId,
1904 e.notationName)
1905 entity.actualEncoding = e.actualEncoding
1906 entity.encoding = e.encoding
1907 entity.version = e.version
1908 entity.ownerDocument = newOwnerDocument
1909 clone.entities._seq.append(entity)
1910 if hasattr(e, '_call_user_data_handler'):
1911 e._call_user_data_handler(operation, n, entity)
1912 else:
1913 # Note the cloning of Document and DocumentType nodes is
Ezio Melotti13925002011-03-16 11:05:33 +02001914 # implementation specific. minidom handles those cases
Martin v. Löwis787354c2003-01-25 15:28:29 +00001915 # directly in the cloneNode() methods.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001916 raise xml.dom.NotSupportedErr("Cannot clone node %s" % repr(node))
Martin v. Löwis787354c2003-01-25 15:28:29 +00001917
1918 # Check for _call_user_data_handler() since this could conceivably
1919 # used with other DOM implementations (one of the FourThought
1920 # DOMs, perhaps?).
1921 if hasattr(node, '_call_user_data_handler'):
1922 node._call_user_data_handler(operation, node, clone)
1923 return clone
1924
1925
1926def _nssplit(qualifiedName):
1927 fields = qualifiedName.split(':', 1)
1928 if len(fields) == 2:
1929 return fields
1930 else:
1931 return (None, fields[0])
1932
1933
Martin v. Löwis787354c2003-01-25 15:28:29 +00001934def _do_pulldom_parse(func, args, kwargs):
Raymond Hettingerff41c482003-04-06 09:01:11 +00001935 events = func(*args, **kwargs)
Fred Drake1f549022000-09-24 05:21:58 +00001936 toktype, rootNode = events.getEvent()
1937 events.expandNode(rootNode)
Martin v. Löwisb417be22001-02-06 01:16:06 +00001938 events.clear()
Fred Drake55c38192000-06-29 19:39:57 +00001939 return rootNode
1940
Martin v. Löwis787354c2003-01-25 15:28:29 +00001941def parse(file, parser=None, bufsize=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001942 """Parse a file into a DOM by filename or file object."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001943 if parser is None and not bufsize:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001944 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001945 return expatbuilder.parse(file)
1946 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001947 from xml.dom import pulldom
Raymond Hettingerff41c482003-04-06 09:01:11 +00001948 return _do_pulldom_parse(pulldom.parse, (file,),
Martin v. Löwis787354c2003-01-25 15:28:29 +00001949 {'parser': parser, 'bufsize': bufsize})
Fred Drake55c38192000-06-29 19:39:57 +00001950
Martin v. Löwis787354c2003-01-25 15:28:29 +00001951def parseString(string, parser=None):
Fred Drakef7cf40d2000-12-14 18:16:11 +00001952 """Parse a file into a DOM from a string."""
Martin v. Löwis787354c2003-01-25 15:28:29 +00001953 if parser is None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001954 from xml.dom import expatbuilder
Martin v. Löwis787354c2003-01-25 15:28:29 +00001955 return expatbuilder.parseString(string)
1956 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001957 from xml.dom import pulldom
Martin v. Löwis787354c2003-01-25 15:28:29 +00001958 return _do_pulldom_parse(pulldom.parseString, (string,),
1959 {'parser': parser})
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001960
Martin v. Löwis787354c2003-01-25 15:28:29 +00001961def getDOMImplementation(features=None):
1962 if features:
Christian Heimesc9543e42007-11-28 08:28:28 +00001963 if isinstance(features, str):
Martin v. Löwis787354c2003-01-25 15:28:29 +00001964 features = domreg._parse_feature_string(features)
1965 for f, v in features:
1966 if not Document.implementation.hasFeature(f, v):
1967 return None
Martin v. Löwis7edbd4f2001-02-22 14:05:50 +00001968 return Document.implementation